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
dd = defaultdict(int)
dd['a'] = 1
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
dd = defaultdict(int)
dd['apple'] = 10
dd['banana'] = 5
regular_dict = dict(dd)
print(f"Type: {type(regular_dict)}")
print(f"Content: {regular_dict}")
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.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
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
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'},
]
grouped = defaultdict(list)
for item in data:
grouped[item['city']].append(item['person'])
result = dict(grouped)
print(result)Output:
{'New York': ['Alice', 'Charlie'], 'London': ['Bob']}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.