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.
Python code
30 linesfrom 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
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
- Use a plain dict with manual counting: `counts = {}; for tag in tags: counts[tag] = counts.get(tag, 0) + 1`.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- 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
Keep learning
Related tutorials and quizzes for this topic.