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.
Python code
20 linesfrom 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
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
- Using a regular dict with setdefault: groups.setdefault(key, set()).add(value)
- 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
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.