How to Compute Set Union of Tags from Multiple Items in Python
Collect all unique tags from a list of dictionaries using set union with update() in Python.
Python code
17 linesitems = [
{"id": 1, "tags": {"python", "web"}},
{"id": 2, "tags": {"web", "api", "sql"}},
{"id": 3, "tags": {"python", "data"}},
]
def get_union_of_tags(item_list):
all_tags = set()
for item in item_list:
all_tags.update(item["tags"])
return all_tags
if __name__ == "__main__":
union_tags = get_union_of_tags(items)
print(sorted(union_tags))
Output
['api', 'data', 'python', 'sql', 'web']
How it works
The set.update() method merges each item's tags into a single all_tags set, automatically removing duplicates. Initializing all_tags as an empty set ensures we start with no elements before accumulating. This approach is efficient for any number of items since set operations have average O(1) insert time. Calling sorted() returns the tags in a predictable order for display.
Common mistakes
- Using `all_tags = all_tags | item['tags']` inside a loop, which creates a new set each time and is less efficient
- Forgetting to initialize `all_tags = set()` before the loop, causing a `NameError`
- Assuming tags are already unique and skipping the union, leading to duplicates
Variations
- Use `set().union(*[item['tags'] for item in items])` for a one-liner approach
- Use a set comprehension: `{tag for item in items for tag in item['tags']}`
Real-world use cases
- Aggregating topic tags from multiple blog posts to build a navigation filter.
- Collecting all permission scopes from several API clients for unified access control.
- Combining feature flags across microservices to determine total enabled functionality.
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.