PYTHON

Simplifying Dictionary Value Assignment with `collections.defaultdict`

Discover how `collections.defaultdict` streamlines dictionary operations by automatically initializing new keys, perfect for grouping data, counting occurrences, or building complex structures.

from collections import defaultdict

# Grouping items by a key
data = [
    {"name": "Alice", "city": "New York"},
    {"name": "Bob", "city": "London"},
    {"name": "Charlie", "city": "New York"},
    {"name": "David", "city": "London"},
]

grouped_by_city = defaultdict(list)
for item in data:
    grouped_by_city[item["city"]].append(item["name"])

print(f"Grouped by city: {dict(grouped_by_city)}")

# Counting occurrences
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_counts = defaultdict(int)
for word in words:
    word_counts[word] += 1

print(f"Word counts: {dict(word_counts)}")

# Using a custom factory function (e.g., for nested dicts)
nested_dict = defaultdict(lambda: defaultdict(int))
nested_dict["user1"]["login_count"] += 1
nested_dict["user1"]["view_count"] += 5
nested_dict["user2"]["login_count"] += 1
print(f"Nested defaultdict: {dict(nested_dict)}")
How it works: `collections.defaultdict` is a subclass of `dict` that overrides one method: `__missing__`. When a key is accessed for the first time, `defaultdict` automatically calls a factory function (provided during initialization) to create a default value for that key, preventing `KeyError`. This is extremely useful for grouping items, counting frequencies, or building complex nested data structures without explicit checks for key existence.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs