Defaultdict in Python (original) (raw)

Last Updated : 09 Apr, 2025

In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.

Key Features of defaultdict:

**Example:

Python `

from collections import defaultdict

d = defaultdict(list)

d['fruits'].append('apple') d['vegetables'].append('carrot') print(d)

print(d['juices'])

`

Output

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

**Explanation: This code creates a **defaultdict with a default value of an empty list. It adds elements to the ‘fruits’ and **‘vegetables’ keys. When trying to access the **‘juices’ key, no **KeyError is raised, and an empty list is returned since it doesn’t exist in the dictionary.

Syntax of DefaultDict in Python

defaultdict(default_factory)

**Parameters:

**Return Value: It returns a dictionary-like object that automatically provides a default value for missing keys, based on the specified callable, instead of raising a KeyError.

How Does defaultdict Work?

When a defaultdict is created, you specify a factory function that will provide the default value for new keys. This factory function could be int, list, str, or any other callable object. For example:

What is default factory in Python dict?

It is a function 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 as default_factory argument

d = defaultdict(lambda: "Not Present") d["a"] = 1 d["b"] = 2

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

`

Use Cases for defaultdict

1. Using List as Default Factory

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

Python `

from collections import defaultdict

d = defaultdict(list)

for i in range(5): d[i].append(i)

print("Dictionary with values as list:") print(d)

`

Output

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

**Explanation: This example demonstrates the use of list as the default factory. A defaultdict is created with list, which means any missing key will automatically have an empty list as its value. The loop appends the value of i to the list of the corresponding key.

2. Using int Default Factory

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

Python `

from collections import defaultdict

d = defaultdict(int)

a = [1, 2, 3, 4, 2, 4, 1, 2]

for i in a:

d[i] += 1
 

print(d)

`

Output

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

**Explanation: This example uses **int as the default factory. **int() returns **0, so missing keys will have a default value of **0. The loop counts the occurrences of each number in the list **a and updates the dictionary accordingly.

3. Using str Default Factory

When the str class is passed as the default_factory argument.

Python `

from collections import defaultdict

Using str as the factory function

sd = defaultdict(str) sd['greeting'] = 'Hello' print(sd)

`

Output

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

Explanation: This example uses str as the default factory. str() returns an empty string, so missing keys will have an empty string as their default value. A value (‘Hello‘) is explicitly set for the key ‘greeting**‘.

Python defaultdict Type for Handling Missing Keys

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

This function is used to provide the default value for the dictionary. It takes **default_factory as an argument and if this argument is **None, a **KeyError is raised otherwise it provides a default value for the given key. This method is basically called by the **__getitem__() 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

d = defaultdict(lambda: "Not Present") d["a"] = 1 d["b"] = 2

print(d.missing('a')) print(d.missing('d'))

`

Output

Not Present Not Present

**Explanation: