Build a defaultdict histogram of categories in Python
Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.
Python code
13 linesfrom collections import defaultdict
def build_category_histogram(items):
"""Count occurrences of each category in a list of items."""
histogram = defaultdict(int)
for item in items:
histogram[item] += 1
return dict(histogram)
if __name__ == "__main__":
categories = ["fruit", "vegetable", "fruit", "dairy", "vegetable", "fruit", "meat"]
result = build_category_histogram(categories)
print(result)
Output
{'fruit': 3, 'vegetable': 2, 'dairy': 1, 'meat': 1}
How it works
defaultdict(int) creates a dictionary where missing keys are automatically assigned a default value of 0 when first accessed or incremented. In the loop, histogram[item] += 1 works without checking if the key exists, because the defaultdict handles initialization. Converting to a plain dict with dict(histogram) is optional but gives a cleaner output without the defaultdict repr. This approach avoids verbose if statements and makes the counting logic concise and readable.
Common mistakes
- Forgetting that `defaultdict(int)` allows direct increment without explicit key check, but it also silently creates keys for any new category.
- Confusing `defaultdict(int)` with `defaultdict(list)` — each has a different default factory.
- Mixing up `defaultdict` and `Counter` — both count, but Counter has extra methods like `most_common`.
Variations
- Use `collections.Counter` for a more feature-rich histogram with `most_common`.
- Use a plain dict and check `if item in histogram` to manually set default.
Real-world use cases
- Counting log entries by severity level in a monitoring system.
- Aggregating product sales by category for a dashboard report.
- Tallying user actions by type in an analytics pipeline.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
- Convert Lists and Dictionaries to Sets in Python easy
Keep learning
Related tutorials and quizzes for this topic.