PYTHON
Simplify Dictionary Default Values with collections.defaultdict
Learn how collections.defaultdict streamlines dictionary operations by automatically providing a default value for missing keys, perfect for grouping or counting.
from collections import defaultdict
# Example 1: Grouping items by a key
# Imagine we have a list of products and their categories
products = [
{'name': 'Laptop', 'category': 'Electronics'},
{'name': 'Mouse', 'category': 'Electronics'},
{'name': 'T-shirt', 'category': 'Apparel'},
{'name': 'Jeans', 'category': 'Apparel'},
{'name': 'Monitor', 'category': 'Electronics'}
]
# Using defaultdict to group products by category
products_by_category = defaultdict(list) # Default factory is 'list', so a new list is created for a missing key
for product in products:
products_by_category[product['category']].append(product['name'])
print("Products grouped by category:")
for category, items in products_by_category.items():
print(f" {category}: {items}")
# Example 2: Counting occurrences (demonstrates defaultdict with 'int')
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# Using defaultdict to count word occurrences
word_counts = defaultdict(int) # Default factory is 'int', so a new int (0) is created for a missing key
for word in words:
word_counts[word] += 1 # No need to check if word exists, it defaults to 0
print("
Word counts using defaultdict:")
for word, count in word_counts.items():
print(f" {word}: {count}")
How it works: The `collections.defaultdict` is a subclass of the built-in `dict` type that overrides one method: `__missing__`. This method is called whenever a requested key is not found, and it's instructed to create a default value for that key and insert it into the dictionary before returning it. This eliminates the need for explicit checks like `if key not in dictionary`, simplifying code for common patterns such as grouping items into lists or counting occurrences by initializing missing keys with a default of 0 (for `int`) or an empty list (for `list`).