How to Group Data by Category in Python

Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

17 lines
Python 3.9+
def group_by_category(data):
    """Group list of (category, value) tuples into dictionaries of lists."""
    groups = {}
    for category, value in data:
        groups.setdefault(category, []).append(value)
    return groups

if __name__ == "__main__":
    items = [
        ("fruit", "apple"),
        ("veg", "carrot"),
        ("fruit", "banana"),
        ("veg", "broccoli"),
        ("fruit", "cherry"),
    ]
    result = group_by_category(items)
    print(result)

Output

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

How it works

The setdefault method returns the existing list for a category if it exists, or creates a new empty list and returns it. Appending to that returned list modifies the dictionary in place. This avoids explicit if key in groups checks and keeps the code concise and readable. The function works with any hashable category type, not just strings. It's a classic pattern for building grouped data structures quickly.

Common mistakes

  • Using `groups[category] = groups.get(category, []) + [value]` which creates new lists each time and is less efficient
  • Forgetting that `setdefault` evaluates its default argument eagerly — use it only with cheap defaults like empty lists
  • Assuming the input order is preserved — Python dicts preserve insertion order, but this isn't guaranteed on older versions

Variations

  1. Use `collections.defaultdict(list)` and `groups[category].append(value)` for a more concise alternative
  2. Use a dict comprehension with `itertools.groupby` if the data is already sorted by category

Real-world use cases

  • Grouping log entries by severity level when analyzing application logs.
  • Batching user events by session ID for analytics processing.
  • Categorizing survey responses by demographic group for reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.