Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8340ade

Browse files
authored
Merge pull request #4 from suman2826/master
added defaultdict library
2 parents e25067c + 0bbfd83 commit 8340ade

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Collections/default_dict_basic.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#It is a subclass of the dict class that returns a dictionary like-object.
2+
#The functionality of both dictionaries and defaultdict are almost same except it never raises a keyerror it provides the deafult value for the key that doesnot exixts.
3+
from collections import defaultdict
4+
def value():
5+
return "No"
6+
7+
d1 = defaultdict(value)
8+
d1["deafult"] = 1
9+
d1["dict"] = 2
10+
print(d1["deafult"]) # 1
11+
print(d1["dict"]) # 2
12+
print(d1["defaultdict"]) # No
13+
14+
#instead of writing it in function we can use lambda parameter
15+
d2 = defaultdict(lambda:"No")
16+
d1["deafult"] = 1
17+
d1["dict"] = 2
18+
print(d1["deafult"]) # 1
19+
print(d1["dict"]) # 2
20+
print(d1["defaultdict"]) # No
21+
22+
#using list as default factory
23+
#when the list class is passed as the argument then a default divt is created with the values that are list
24+
d3 = defaultdict(list)
25+
for i in range(5):
26+
d3[i].append(i)
27+
print(d3) #{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
28+
29+
#using int as default factory
30+
#when the int class is passed then a defaultdict is created with default as zero.
31+
d4 = defaultdict(int)
32+
nums = [1,2,3,4,1,4,3,5]
33+
for num in nums:
34+
d4[i] += 1
35+
print(d4) #{1: 2, 2: 1, 3: 2, 4: 2, 5: 1})
36+
37+
38+
39+

0 commit comments

Comments
 (0)