How to Use defaultdict(set) in Python to Group Unique Values

Group key-value pairs into a dictionary of sets, automatically creating a new set for each key using defaultdict.

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

Python code

20 lines
Python 3.9+
from collections import defaultdict

def track_groups(pairs):
    groups = defaultdict(set)
    for key, value in pairs:
        groups[key].add(value)
    return groups

if __name__ == "__main__":
    data = [
        ("fruit", "apple"),
        ("fruit", "banana"),
        ("fruit", "apple"),
        ("veg", "carrot"),
        ("veg", "broccoli"),
        ("fruit", "cherry"),
    ]
    result = track_groups(data)
    for category, items in sorted(result.items()):
        print(f"{category}: {sorted(items)}")

Output

stdout
fruit: ['apple', 'banana', 'cherry']
veg: ['broccoli', 'carrot']

How it works

defaultdict(set) creates a dictionary that, when a missing key is accessed, automatically inserts a new empty set as the value. This lets you call .add() directly without checking if the key exists. Since sets store unique items, duplicate values like 'apple' are added only once per key. Sorting the items before printing makes the output deterministic.

Common mistakes

  • Using a list instead of a set, which would store duplicates
  • Forgetting to import defaultdict from collections
  • Calling groups[key] = groups[key].add(value), which sets the value to None
  • Assuming iteration order of sets is always sorted

Variations

  1. Using a regular dict with setdefault: groups.setdefault(key, set()).add(value)
  2. Using dict comprehension when all values are known upfront

Real-world use cases

  • Grouping log events by service name while deduplicating unique error messages
  • Building an index of tags per document from a dataframe of tag assignments
  • Aggregating user permissions from a list of role assignments, keeping only unique permissions

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.