-
-
Save IndhumathyChelliah/0e4710cb3b3599fa22cadd846cea47e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
#default_factory is mentioned as 'int' class | |
d=defaultdict(int) | |
d['a']=1 | |
d['b']=2 | |
#default_factory is given as 'int' class. | |
print (d)#Output:defaultdict(<class 'int'>, {'a': 1, 'b': 2}) | |
#Returns the default value of int class which is 0. | |
print (d.__missing__('a')) #Output:0 | |
print (d.__missing__('z'))#Output:0 | |
#__getitem__() ->If key exists return the value else it will call __missing__() method. | |
print (d.__getitem__('a'))#Output:0 | |
print (d.__getitem__('z'))#Output:0 | |
#In regular dictionary | |
d1={'a':1,'b':2} | |
print (d1)#Output:{'a': 1, 'b': 2} | |
#__getitem__() -> If key exists return the value, else returns KeyError. | |
print (d1.__getitem__('a'))#Output:1 | |
#print (d1.__getitem__('z'))#Output:KeyError: 'z' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment