Saturday 9 January 2021

Defaultdict in Python

 

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.


from collections import defaultdict

defDict = defaultdict( int )
defDict["alpha"] = 1
defDict["beta"] = 2
print(defDict["gamma"])
print(defDict["alpha"])