How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
Python code
17 linesdef 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
{'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
- Use `collections.defaultdict(list)` and `groups[category].append(value)` for a more concise alternative
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.