A store needs products grouped into stationery and electronics.
What You Need to Understand
Group records by a category key by building a dictionary whose values are lists. For each record, look up the category and append the record to that category's list.
When to Use It
A store needs products grouped into stationery and electronics.
Step-by-Step Python Example
products = [
{"name": "Pen", "category": "Stationery"},
{"name": "Mouse", "category": "Electronics"},
{"name": "Paper", "category": "Stationery"},
]
groups = {}
for product in products:
groups.setdefault(product["category"], []).append(product["name"])
for category, names in groups.items():
print(category, ", ".join(names))
How the Example Works
The same category key points to one growing list, so Pen and Paper appear together.
Example Output
Stationery Pen, Paper
Electronics Mouse
{'IT': 1, 'HR': 1}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
records = [("Maya", "IT"), ("Noa", "HR")]
groups = {}
for name, department in records:
groups.setdefault(department, []).append(name)
print({department: len(names) for department, names in groups.items()})
Important Behavior and Edge Cases
Validate that each record has a meaningful category. Do not use a shared default list created outside the loop for all categories.
Try It Yourself
Group employees by department and count how many records belong to each group.
Common Beginner Mistakes
- Validate that each record has a meaningful category. Do not use a shared default list created outside the loop for all categories.
- Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.
Key Takeaways
- Group records by a category key by building a dictionary whose values are lists.
- The same category key points to one growing list, so Pen and Paper appear together.
- Validate that each record has a meaningful category.