How to Use defaultdict in Python: Simple Guide with Examples
Use
defaultdict from the collections module to create a dictionary that provides a default value for missing keys automatically. Initialize it with a function that returns the default value, so you avoid KeyError when accessing keys that don't exist.Syntax
The defaultdict is created by importing it from the collections module and initializing it with a default factory function. This function returns the default value for any missing key.
defaultdict(default_factory): Creates a dictionary where missing keys returndefault_factory()value.default_factory: A function likeint,list, or a custom function that returns the default value.
python
from collections import defaultdict d = defaultdict(int) # int() returns 0 as default print(d['missing_key']) # prints 0
Output
0
Example
This example shows how to count the frequency of letters in a word using defaultdict. It automatically starts counts at zero, so you don't need to check if the letter is already in the dictionary.
python
from collections import defaultdict word = 'banana' letter_count = defaultdict(int) for letter in word: letter_count[letter] += 1 print(dict(letter_count))
Output
{'b': 1, 'a': 3, 'n': 2}
Common Pitfalls
One common mistake is to use a regular dictionary and try to access or increment a key that doesn't exist, which causes a KeyError. Another is to forget that defaultdict requires a callable for the default factory, not a value.
Wrong way:
counts = {}
counts['a'] += 1 # KeyError because 'a' is missingRight way with defaultdict:
python
from collections import defaultdict counts = defaultdict(int) counts['a'] += 1 print(counts['a'])
Output
1
Quick Reference
| Feature | Description | Example |
|---|---|---|
| default_factory | Function returning default value for missing keys | int, list, lambda: 'N/A' |
| Access missing key | Returns default value instead of KeyError | d['missing'] returns 0 if int() used |
| Increment counts | Easily count items without key checks | d[key] += 1 |
| Custom default | Use any function for default values | defaultdict(lambda: 'unknown') |
Key Takeaways
Use defaultdict to avoid KeyError by providing default values automatically.
Initialize defaultdict with a function like int or list to set default values.
defaultdict is perfect for counting or grouping data without manual key checks.
Remember default_factory must be a callable, not a direct value.
Convert defaultdict to dict if you want a regular dictionary output.