How to Count Tags with Sets and Dictionaries in Python

Count tag frequencies and collect unique tags from a list of dictionaries using Counter and sets in Python.

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

Python code

30 lines
Python 3.9+
from collections import Counter
import json


def count_tags(entries):
    """Count tag frequencies across a list of entry dicts, using sets/dicts."""
    tag_counter = Counter()
    all_tags = set()
    for entry in entries:
        tags = set(entry["tags"])
        all_tags.update(tags)
        tag_counter.update(tags)
    return dict(tag_counter), sorted(all_tags)


if __name__ == "__main__":
    sample_data = [
        {"title": "Apple pie", "tags": ["baking", "dessert"]},
        {"title": "Beef stew", "tags": ["cooking", "dinner"]},
        {"title": "Fruit salad", "tags": ["dessert", "fresh"]},
        {"title": "Chicken curry", "tags": ["cooking", "spicy", "dinner"]},
    ]

    frequencies, unique = count_tags(sample_data)
    print("Tag frequencies:", frequencies)
    print("Unique tags:", unique)

    with open("tag_output.json", "w") as f:
        json.dump(frequencies, f, indent=2)
    print("Saved tag_output.json")

Output

stdout
Tag frequencies: {'baking': 1, 'dessert': 2, 'cooking': 2, 'dinner': 2, 'fresh': 1, 'spicy': 1}
Unique tags: ['baking', 'cooking', 'dessert', 'dinner', 'fresh', 'spicy']
Saved tag_output.json

How it works

This code uses collections.Counter to efficiently tally tag occurrences. A set collects unique tags, and update() merges new tags without duplication. Converting the counter to a dict gives a plain dictionary, and sorting the set returns an ordered list. The __main__ block demonstrates with sample data and writes the frequency dictionary to a JSON file.

Common mistakes

  • Forgetting to convert entry['tags'] to a set before updating, causing double counts? Actually it's fine, but missing duplicates handling.
  • Assuming `json.dump` overwrites the file without opening in 'w' mode.
  • Not sorting the unique set, leading to unpredictable order.
  • Using `set.update()` with a list that contains unhashable elements.

Variations

  1. Use a plain dict with manual counting: `counts = {}; for tag in tags: counts[tag] = counts.get(tag, 0) + 1`.
  2. Collect unique tags with a list comprehension and `sorted(set(...))`.

Real-world use cases

  • Aggregating hashtags from social media posts to find trending topics.
  • Grouping product categories in an e-commerce inventory to analyze distribution.
  • Summarizing error codes from log entries to prioritize debugging efforts.

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.