Build a defaultdict histogram of categories in Python

Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 10 views 0 copies

Python code

13 lines
Python 3.9+
from 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

stdout
{'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

  1. Use `collections.Counter` for a more feature-rich histogram with `most_common`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.