Defaultdict in Python

Python Defaultdict is a container-like dictionaries present in the module collections.

  • It is a sub-class of the dictionary class that returns a dictionary-like object.
  • The difference from dictionary is, It provides a default value for the key that does not exist and never raises a KeyError.

Python

from collections import defaultdict

# Create a defaultdict with a default
# value of an empty list
d = defaultdict(list)

# Add elements to the defaultdict and print it
d['fruits'].append('apple')
d['vegetables'].append('carrot')
print(d)

# No key error raised here and an empty list
# is printed
print(d['juices'])
Output

defaultdict(<class 'list'>, {'fruits': ['apple'], 'vegetables': ['carrot']})
[]

Syntax of DefaultDict in Python

Syntax: defaultdict(default_factory)
Parameters:  

  • default_factory: A function/method returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.

Here, list is a factory function/method that defines the default value. Each time a key is accessed that doesn’t exist, it will automatically be assigned an empty list.

How Does defaultdict Work?

When a defaultdict is created, you specify a factory function/method that will provide the default value for new keys. This factory function/method can happen int, list, str, or any other callable object.

For example:

  • Using int: If you use int when the factory function, the default value will be 0 (since int() returns 0).
  • Using list: If you use list when the factory function, the default value will be an empty list ([]).
  • Using str: If you use str, the default value will be an empty string ('').

What is default factory in Python dict?

It is a function/method returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.

Python

from collections import defaultdict

    
# Defining the dict and passing 
# lambda when default_factory argument
d = defaultdict(lambda: "Not Present")
d["a"] = 1
d["b"] = 2

print(d["a"])
print(d["b"])
print(d["c"])
Output

1
2
Not Present

Python defaultdict Type for Handling Missing Keys

Defaultdict adds one writable instance variable and one functions/method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the functions/method provided is __missing__.

This function/method is have used to provide the default value for the dictionary. This function/method takes default_factory when an argument and if this argument is None, a KeyError is raised otherwise it provides a default value for the given key. This functions/method is basically called by the __getitem__() functions/method of the dict class when the requested key is not found. __getitem__() raises or return the value returned by the __missing__(). method.

Python

from collections import defaultdict
  
# Defining the dict
d = defaultdict(lambda: "Not Present")
d["a"] = 1
d["b"] = 2

# Provides the default value 
# for the key
print(d.__missing__('a'))
print(d.__missing__('d'))
Output

Not Present
Not Present

Common Use Cases for defaultdict

Using List when Default Factory

When the list class is passed when the default_factory argument, then a defaultdict is created with the values that are list.

Python

from collections import defaultdict

# Defining a dict
d = defaultdict(list)

for i in range(5):
    d[i].append(i)
    
print("Dictionary with values when list:")
print(d)
Output

Dictionary with values when list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})

Using int Default Factory

When the int class is passed when the default_factory argument, then a defaultdict is created with default value when zero.

Python

from collections import defaultdict
 
# Defining the dict
d = defaultdict(int)
 
L = [1, 2, 3, 4, 2, 4, 1, 2]
 
# Iterate through the list
# for keeping the count
for i in L:
     
    # The default value is 0
    # so there is no need to 
    # enter the key first
    d[i] += 1
     
print(d)
Output

defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

Using str Default Factory

When the str class is passed when the default factory argument.

Python

from collections import defaultdict

# Using str when the factory function
str_defaultdict = defaultdict(str)
str_defaultdict['greeting'] = 'Hello'
print(str_defaultdict)
Output

defaultdict(<class 'str'>, {'greeting': 'Hello'})

Defaultdict in Python – FAQs

What is Defaultdict in Python Keyerror?

Defaultdict is a subclass of Python’s built-in dict class. It overrides the __missing__ functions/method to provide a default value for missing keys, preventing KeyError. If a key is not found in the dictionary, defaultdict automatically inserts it with a default value.

What is Defaultdict subclass in Python?

defaultdict is a subclass of the dict class in Python, found in the collections module. It allows you to specify a default factory function/method that provides default values for missing keys.

from collections import defaultdict
# Example with list when the default factory
dd = defaultdict(list)
dd[‘missing_key’].append(1)
print(dd) # Output: defaultdict(<class ‘list’>, {‘missing_key’: [1]})

What is the difference between Setdefault and Defaultdict in Python?

setdefault is a functions/method of the dict class. It inserts a key with a specified default value if the key is not already present.

d = {}
d.setdefault(‘key’, []).append(1)
print(d) # Output: {‘key’: [1]}
defaultdict is a subclass of dict that provides a default value for a missing key without explicitly checking for its presence.
from collections import defaultdict
dd = defaultdict(list)
dd[‘key’].append(1)
print(dd) # Output: defaultdict(<class ‘list’>, {‘key’: [1]})

What is the difference between Defaultdict and dict in Python typing?

Dict: A standard dictionary without automatic default values for missing keys.

d = {}
# Accessing a missing key will raise KeyError
defaultdict: A dictionary with a default factory function/method that automatically creates values for missing keys.
from collections import defaultdict
dd = defaultdict(int)
# Accessing a missing key will return 0 (default value provided by int())

Why we use Setdefault in Python?

setdefault is have used to insert a key with a default value if the key is not already in the dictionary. This is useful for avoiding repeated key existence checks and manual insertion.

d = {}
d.setdefault(‘key’, []).append(1)
d.setdefault(‘key’, []).append(2)
print(d) # Output: {‘key’: [1, 2]}

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the