Python collections defaultdict() Method with Examples

Defaultdict:

Defaultdict is a container similar to dictionaries seen in module collections. Defaultdict is a dictionary subclass that returns a dictionary-like object. Except for the fact that defualtdict never raises a KeyError, the behaviour of dictionaries and defualtdict is nearly identical. It gives a default value for a non-existent key.

Syntax:

defaultdict(default_factory)

Parameters:

default_factory:

A function that returns the dictionary's default value. 
If this parameter is missing, the dictionary will throw a KeyError.

Collections defaultdict() Method with Examples in Python

i)Default Dict Example

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a function noKey() that returns some string/value if the key is not present in the dictionary.
  • Inside the function return some random statement(Related to Key is missing)
  • Create a dictionary by passing the above noKey() function as argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Print the keys which are present in the dictionary.
  • Print the keys which are not present in the above dictionary then it prints the return value of the noKey() function.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a function noKey() that returns some string/value
# if the key is not present in the dictionary.


def noKey():
    # Inside the function return some random statement(Related to Key is missing)
    return "The Given Key is missing"


# Create a dictionary by passing the above noKey() function as argument to defaultdict.
defaultDictionary = defaultdict(noKey)
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456

# Print the keys which are present in the dictionary.
print(defaultDictionary["hello"])
print(defaultDictionary["is"])
# Print the keys which are not present in the above dictionary
# then it prints the return value of the noKey() function.
print(defaultDictionary["good"])

Output:

340
222
The Given Key is missing

ii)__missing__() function in defaultDict

This function is used to set the dictionary’s default value. If the default_factory is None, a KeyError is generated; otherwise, the function returns a default value for the specified key. When the specified key cannot be found, the dict class’s __getitem__() method invokes this method. The value returned by the __missing__() method is raised or returned by __getitem__().

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a dictionary by passing the lambda function as an argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Pass the above keys to __missing__() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a dictionary by passing the lambda function as an argument to defaultdict.
defaultDictionary = defaultdict(lambda: "The Given Key is missing")
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456
# Pass the above keys to __missing__() function and print it.
print(defaultDictionary.__missing__('hello'))
print(defaultDictionary.__missing__('this'))
print(defaultDictionary.__missing__('is'))
print(defaultDictionary.__missing__('python-programs'))

Output:

The Given Key is missing
The Given Key is missing
The Given Key is missing
The Given Key is missing

iii)Using List as default_factory

When the list class is specified as the default factory option, a defaultdict containing list values is generated.

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a dictionary by passing the list as an argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Print the dictionary.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a dictionary by passing the list as an argument to defaultdict.
defaultDictionary = defaultdict(list)
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456
# Print the dictionary.
print(defaultDictionary)

Output:

defaultdict(<class 'list'>, {'hello': 340, 'this': 400, 'is': 222, 'python-programs': 456})