How to Group Data by Category in Python with a Split Data Helper

This code groups a list of (category, item) pairs into a dictionary where each key is a category and each value is a list of items belonging to that category.

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

Python code

26 lines
Python 3.9+
def split_data(categories):
    """
    Group data items into buckets based on a key function.
    Returns a dict where keys are bucket names and values are lists of items.
    """
    buckets = {}
    for category, item in categories:
        if category not in buckets:
            buckets[category] = []
        buckets[category].append(item)
    return buckets


if __name__ == "__main__":
    data = [
        ("fruits", "apple"),
        ("vegetables", "carrot"),
        ("fruits", "banana"),
        ("vegetables", "broccoli"),
        ("fruits", "cherry"),
        ("dairy", "milk"),
    ]

    result = split_data(data)
    for category in sorted(result):
        print(f"{category}: {sorted(result[category])}")

Output

stdout
dairy: ['milk']
fruits: ['apple', 'banana', 'cherry']
vegetables: ['broccoli', 'carrot']

How it works

The split_data function iterates over each tuple in the input list, unpacking it into category and item. It uses a dictionary buckets to accumulate items under their category keys. The if category not in buckets check ensures we create an empty list for each new category before appending. The main block demonstrates the function with sample data and prints the buckets in sorted order, sorting the items within each category for consistent output. This pattern is a common way to group data without external libraries.

Common mistakes

  • Forgetting to initialize the list for a new category before appending, causing a KeyError.
  • Assuming the input list is sorted by category, leading to unexpected bucket order.
  • Modifying the original data list while iterating, which can skip items.
  • Not handling non-tuple iterables within the list, causing unpacking errors.

Variations

  1. Use dictionaries with `.setdefault()` to simplify the grouping: `buckets.setdefault(category, []).append(item)`.
  2. Use `collections.defaultdict(list)` to avoid manual initialization: results in a default factory that creates lists on missing keys.

Real-world use cases

  • Grouping log entries by severity level for monitoring dashboards.
  • Partitioning user events by session ID to analyze behavior patterns.
  • Organizing product SKUs by warehouse zone for inventory management.

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.