Defaultdict is a subclass of built-in dict class that returns dictionary-like object. It is present in Collections module.
Functionality
Both dict and defaultdict have similar functionalities except that in defaultdict a default value is provided for the key that does not exist.
Note: For more information, please check Python Dictionaries .
Creating Defaultdict
Default dict can be created using built-in defalutdict( ) function:
# importing defaultdict from the collections module
from collections
import defaultdict
def default_factory( ):
return "Deafult Value"
defDict = defaultdict( default_factory )
defDict["alpha"] = 0
defDict["beta"] = 1
print(defDict["gamma"])
print(defDict["alpha"])
default_factory: An attribute which is a function
returning the default value for the dictionary defined. If this argument is
absent then the dictionary raises a KeyError
.
If default_factory attribute is absent: KeyError
is raised
Using int as default_factory
When the int class is used as a default_factory and passed to the defaultdict( ), zero is used as default value for the key that does not exists.
defDict = defaultdict( int )
defDict["alpha"] = 1
defDict["beta"] = 2
print(defDict["alpha"])
Helpful article
ReplyDeleteThanks for the feedback!
DeleteWell written and helpful
ReplyDeleteThanks for the feedback!
DeleteO my god sir u made my life vohoooooooo
ReplyDeleteThanks for the feedback!
DeleteWow its good sir
ReplyDeleteNice post 👍
ReplyDeleteThanks for the feedback!
DeleteVery informative
ReplyDeleteThanks for the feedback!
DeleteGood explanation
ReplyDeleteThanks for the feedback!
DeleteHelpful article
ReplyDeleteThanks for the feedback!
DeleteInformative post indeed, I’ve being in and out reading posts regularly and I see a lot of engaging people sharing things and majority of the shared information is very valuable and so, here’s my fine read
ReplyDeletejava training institute in delhi