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"])

 


 

 

16 comments:

  1. O my god sir u made my life vohoooooooo

    ReplyDelete
  2. Informative 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

    java training institute in delhi

    ReplyDelete