Prefer defaultdict for Handling Missing Keys in Python

Posted by Afsal on 09-May-2025

Hi Pythonistas!

When working with dictionaries, one common headache is handling missing keys.Manually checking and initializing every key clutters your code.

Instead, Python offers a beautiful tool: defaultdict from the collections module! 

The Old (Tedious) Way: Manual Checks

In [4]: words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

In [5]: word_counts = {}

In [6]: for word in words:
   ...:     if word not in word_counts:
   ...:         word_counts[word] = 1
   ...:     else:
   ...:         word_counts[word] += 1
   ...: 

In [7]: word_counts
Out[7]: {'apple': 3, 'banana': 2, 'orange': 1}

In [8]: 


✅ Works, but the manual checking (if word not in word_counts) is extra noise.
❌ Harder to read, harder to maintain.

The Better Way: Use defaultdict

In [9]: from collections import defaultdict
   ...: 
   ...: words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
   ...: 
   ...: word_counts = defaultdict(int)
   ...: for word in words:
   ...:     word_counts[word] += 1
   ...: 
   ...: print(word_counts)
defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'orange': 1})

In [10]: 

In [10]: 

✅ Cleaner
✅ Shorter
✅ Focuses purely on counting words!

How defaultdict Works
If you try to access a missing key, it automatically creates a default value (like 0, [], set(), etc.)

No manual checks needed. It calls the function you specify (like int, list, set) to create the missing value.

Grouping Made Easy

In [10]: names = ['Alice', 'Bob', 'Alice', 'David', 'Bob']
    ...: 
    ...: groups = defaultdict(list)
    ...: for name in names:
    ...:     groups[name[0]].append(name)
    ...: 

In [11]: groups
Out[11]: 
defaultdict(list,
            {'A': ['Alice', 'Alice'], 'B': ['Bob', 'Bob'], 'D': ['David']})

Grouping by the first letter — and no need to initialize lists manually! ✨

✅ Best Practice
Prefer defaultdict when you're handling missing keys.Use appropriate default factories like int, list, or set.

Cleaner code = fewer bugs + happier future you.