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.

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

Python code

17 lines
Python 3.9+
items = [
    {"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

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

  1. Use `set().union(*[item['tags'] for item in items])` for a one-liner approach
  2. 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

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.