How to Convert a defaultdict to a Regular Dictionary in Python
In Python, the collections.defaultdict is a subclass of the built-in dict that automatically provides default values for missing keys. While this is incredibly useful for aggregating data (like counting or grouping), specific libraries, APIs, or serialization processes (like JSON conversion) often require a standard dict.
This guide explains how to convert a defaultdict into a regular dictionary and explores common scenarios where this conversion is necessary.
Understanding the Difference
The primary difference between a defaultdict and a standard dict is how they handle missing keys.
defaultdict: Calls a factory function (likeint,list, orlambda) to generate a value if the key is missing.dict: Raises aKeyErrorif you access a missing key.
Converting to a regular dictionary is often done at the end of a data processing pipeline to "freeze" the data structure and prevent accidental creation of new keys.
from collections import defaultdict
# A defaultdict that defaults missing values to 0
dd = defaultdict(int)
dd['a'] = 1
# ✅ Correct: Accessing a missing key creates it automatically
print(f"Missing key 'b': {dd['b']}")
print(f"Current defaultdict: {dd}")
Output:
Missing key 'b': 0
Current defaultdict: defaultdict(<class 'int'>, {'a': 1, 'b': 0})
Method 1: Using the dict() Constructor (Recommended)
The most Pythonic and efficient way to convert a defaultdict (or any iterable of key-value pairs) into a standard dictionary is using the built-in dict() constructor.
from collections import defaultdict
# 1. Setup a defaultdict
dd = defaultdict(int)
dd['apple'] = 10
dd['banana'] = 5
# 2. Convert to regular dict
regular_dict = dict(dd)
print(f"Type: {type(regular_dict)}")
print(f"Content: {regular_dict}")
# ⛔️ Error check: Accessing a missing key now raises KeyError
try:
print(regular_dict['cherry'])
except KeyError:
print("Error: Key 'cherry' not found in regular dict.")
Output:
Type: <class 'dict'>
Content: {'apple': 10, 'banana': 5}
Error: Key 'cherry' not found in regular dict.
This method creates a shallow copy. If your dictionary contains mutable objects (like lists), the new dictionary points to the same lists as the old one.
Method 2: Using Dictionary Comprehension
If you need to filter data or transform keys/values during the conversion process, dictionary comprehension provides more control.
from collections import defaultdict
dd = defaultdict(int)
dd['a'] = 1
dd['b'] = 2
# ✅ Correct: Creating a new dict, potentially modifying items
# Example: Convert keys to uppercase during conversion
regular_dict = {k.upper(): v for k, v in dd.items()}
print(regular_dict)
Output:
{'A': 1, 'B': 2}
Practical Examples: Counting and Grouping
Example 1: Counting Occurrences
A common pattern is using defaultdict(int) to count items, then converting to dict for the final result.
from collections import defaultdict
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'date']
word_counts = defaultdict(int)
for word in words:
word_counts[word] += 1
# Convert for final output
final_counts = dict(word_counts)
print(final_counts)
Output:
{'apple': 2, 'banana': 2, 'cherry': 1, 'date': 1}
Example 2: Grouping Data
Using defaultdict(list) allows you to append items without initializing lists manually.
from collections import defaultdict
data = [
{'city': 'New York', 'person': 'Alice'},
{'city': 'London', 'person': 'Bob'},
{'city': 'New York', 'person': 'Charlie'},
]
# Group people by city
grouped = defaultdict(list)
for item in data:
grouped[item['city']].append(item['person'])
# Convert to standard dict for usage in APIs or return values
result = dict(grouped)
print(result)
Output:
{'New York': ['Alice', 'Charlie'], 'London': ['Bob']}
Nested Defaultdicts: If you have a defaultdict(defaultdict), using dict() on the outer level does not convert the inner dictionaries. The values inside will remain defaultdict objects. You would need a recursive function or json.loads(json.dumps(dd)) to fully convert nested structures.
Conclusion
Converting defaultdict to dict is a best practice when finalizing data structures to ensure strict key lookups.
- Use
dict(my_defaultdict)for a quick, readable, and efficient conversion. - Use Dictionary Comprehension if you need to filter or transform data during the conversion.
- Remember that conversion removes the "default value" behavior, causing
KeyErroron missing keys.