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.
Python code
26 linesdef 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
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
- Use dictionaries with `.setdefault()` to simplify the grouping: `buckets.setdefault(category, []).append(item)`.
- 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
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.