Group Data by Key in Python with Dictionaries and Sets
Group items into a dictionary of sets using a key function, a beginner-friendly pattern for organizing data by categories.
Python code
20 linesdef group_data(items, key_func):
"""Group items into a dictionary of sets based on a key function."""
grouped = {}
for item in items:
key = key_func(item)
if key not in grouped:
grouped[key] = set()
grouped[key].add(item)
return grouped
if __name__ == "__main__":
# Example: group numbers by even/odd
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
parity = lambda n: "even" if n % 2 == 0 else "odd"
result = group_data(numbers, parity)
print(result)
print("Even group:", sorted(result["even"]))
print("Odd group:", sorted(result["odd"]))
Output
{'odd': {1, 3, 5, 7, 9}, 'even': {2, 4, 6, 8, 10}}
Even group: [2, 4, 6, 8, 10]
Odd group: [1, 3, 5, 7, 9]
How it works
The group_data function builds a dictionary where each key is produced by key_func and each value is a set of items sharing that key. Sets automatically remove duplicate items, which is handy when input contains repeats. The if key not in grouped check lazily initializes each set only on first encounter, avoiding unnecessary set creation. Using set() as the container makes membership checks fast and ensures each item appears once per group. This pattern is a clean, readable way to categorize data without extra dependencies.
Common mistakes
- Forgetting to initialize the set for a new key before adding items
- Using a list instead of a set, which keeps duplicates and loses the deduplication benefit
- Assuming the output order is sorted — dictionaries and sets are unordered unless explicitly sorted
- Mutating the returned dictionary and unintentionally affecting the original data
Variations
- Use `defaultdict(set)` from collections to avoid manual key initialization
- Group by a simple attribute like `len` or `item[0]` instead of a custom lambda
Real-world use cases
- Categorizing logs by severity level (info, warning, error) for batch analysis.
- Grouping user transactions by currency code to compute per-currency totals.
- Organizing inventory items by category to apply bulk discount rules.
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.