Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Last active July 15, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/0e4710cb3b3599fa22cadd846cea47e4 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/0e4710cb3b3599fa22cadd846cea47e4 to your computer and use it in GitHub Desktop.
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