PYTHON

Grouping Data with Python's collections.defaultdict

Learn how to efficiently group elements by a common key using Python's `collections.defaultdict`, a powerful tool for structuring data in web applications.

from collections import defaultdict

data = [
    {"id": 1, "category": "fruit", "name": "Apple"},
    {"id": 2, "category": "vegetable", "name": "Carrot"},
    {"id": 3, "category": "fruit", "name": "Banana"},
    {"id": 4, "category": "vegetable", "name": "Broccoli"},
    {"id": 5, "category": "fruit", "name": "Orange"}
]

# Group items by category
grouped_data = defaultdict(list)
for item in data:
    grouped_data[item["category"]].append(item)

print(dict(grouped_data))
How it works: `defaultdict` from the `collections` module simplifies grouping items. When you try to access a key that doesn't exist, it automatically creates it with a default value (in this case, an empty list), allowing you to append items without explicit `if key not in dict:` checks. This is highly useful for organizing data from databases or APIs, common tasks in web development.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs