Python collections.defaultdict



The Python defaultdict() is a container, which is similar to the dictionaries. It is present in the collection module. It is a subclass of the dictionary class which returns a dictionary as object.

The functionality of the both dictionaries and defaultdict are similar, the only difference is the defualtdict does not raise a KeyError. It provides a default value for the key which does not exists.

Syntax

Following is a syntax of the Python defaultdict() class −

defaultdict(default_factory)

Parameters

Following is the parameters accepted by this class −

  • default_factory : This is a function which returns a default value for the defined dictionary . If this argument is not passed than the function raises a KeyError.

Return Value

This class returns a <collections.defaultdict> object.

Example

Following is an basic example of the Python defaultdict() class −

from collections import defaultdict
def default():
   return 'Key not found'

dic1 = defaultdict(default)
dic1[1] = 'one'
dic1[2] = 'two'
dic1[3] = 'Three'
print(dic1)
print(dic1[5])

Following is the output of the above code −

defaultdict(<function default at 0x000002040ACC8A40>, {1: 'one', 2: 'two', 3: 'Three'})
Key not found

Using defaultdict() with __missing__()

The __missing__() method is used to define the behavior of default_factory that is passed as an argument in the defaultdict(). If the default_factory is None this method generates a KeyError.

Example

Following is an example of the defaultdict() with __missing__() method −

from collections import defaultdict
def default():
   return 'Key not found'

#defined defaultdict
dic1 = defaultdict(default)
dic1[1] = 'Python'
dic1[2] = 'Java'
dic1[3] = 'C++'
print(dic1)
#__missing__() function
var1 = dic1.__missing__(1)
print(var1)

Following is the output of the above code −

defaultdict(<function default at 0x000001F92A5F8A40>, {1: 'Python', 2: 'Java', 3: 'C++'})
Key not found

List as default_factory

In defaultdict(), we can pass the list as a default_factory. When we try to find the value of the key which is not present in the dictionary it will return an empty list.

Example

Here, we have defined a list of tuple and each tuple containing two values, keys and values. And we have passed the list as argument in the defaultdict() function and appended items into the dictionary −

# Python program to demonstrate
# defaultdict
from collections import defaultdict
s = [('Python', 90), ('Java', 85), ('Python', 75), ('C++', 80), ('Java', 120)]
dict1 = defaultdict(list)
for k, v in s:
   dict1[k].append(v)

sorted(dict1.items())
print(dict1)
print("Key is not present in the dictionary :",dict1['html'])

Following is the output of the above code −

defaultdict(<class 'list'>, {'Python': [90, 75], 'Java': [85, 120], 'C++': [80]})
[]

Integer Value as default_factory

In defaultdict(), when we can pass int as an argument, it makes the function countable. When we try to find a key which is not present it will return zero.

Example

Here, we have append the characters into dictionary and when we found the key value which is not present in the dictionary resulted 0

from collections import defaultdict
var1 = 'Hello'
dict1 = defaultdict(int)
for k in var1:
   dict1[k] += 1

sorted(dict1.items())
print(dict1)
#Value of key which is not found in dictionary
print("Key Value :", dict1['k'])

Following is the output of the above code −

defaultdict(<class 'int'>, {'H': 1, 'e': 1, 'l': 2, 'o': 1})
Key Value : 0
python_modules.htm
Advertisements