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.

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

Python code

20 lines
Python 3.9+
def 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

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

  1. Use `defaultdict(set)` from collections to avoid manual key initialization
  2. 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

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.