Practical Use Cases
Counting Occurrences
One common use case for defaultdict
is counting the occurrences of elements in a list or other iterable. By using a defaultdict(int)
, you can easily keep track of the count for each element without having to check if the key already exists in the dictionary.
from collections import defaultdict
words = ['apple', 'banana', 'cherry', 'apple', 'banana', 'date']
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
print(dict(word_count))
## Output: {'apple': 2, 'banana': 2, 'cherry': 1, 'date': 1}
Grouping Data
Another useful application of defaultdict
is grouping data by a certain key, where the values are stored in lists. This can be particularly helpful when you need to organize data based on some criteria.
from collections import defaultdict
data = [
{'name': 'Alice', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'New York'},
{'name': 'David', 'age': 40, 'city': 'Los Angeles'},
]
grouped_data = defaultdict(list)
for item in data:
grouped_data[item['city']].append(item)
print(dict(grouped_data))
## Output: {'New York': [{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}],
## 'Los Angeles': [{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]}
Nested Dictionaries
defaultdict
can also be useful when working with nested dictionaries. By using a defaultdict(dict)
, you can automatically create new nested dictionaries when accessing a key that doesn't exist.
from collections import defaultdict
data = {
'fruit': {
'apple': 2,
'banana': 3,
},
'vegetable': {
'carrot': 5,
'broccoli': 4,
},
}
nested_dd = defaultdict(dict)
for category, items in data.items():
for item, count in items.items():
nested_dd[category][item] = count
print(dict(nested_dd))
## Output: {'fruit': {'apple': 2, 'banana': 3}, 'vegetable': {'carrot': 5, 'broccoli': 4}}
By exploring these practical use cases, you can see how defaultdict
can simplify your Python code and help you handle missing keys more effectively.