PYTHON

Grouping Items by Key with defaultdict

Efficiently group a list of dictionaries or objects by a common key into a dictionary of lists using Python's `collections.defaultdict` for simplified data organization.

from collections import defaultdict

data = [
    {"category": "Fruit", "item": "Apple"},
    {"category": "Vegetable", "item": "Carrot"},
    {"category": "Fruit", "item": "Banana"},
    {"category": "Vegetable", "item": "Broccoli"},
    {"category": "Dairy", "item": "Milk"},
]

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

# Convert defaultdict to a regular dict if needed
final_grouped_data = dict(grouped_data)
print(f"Grouped Data: {final_grouped_data}")
# Expected output: {'Fruit': ['Apple', 'Banana'], 'Vegetable': ['Carrot', 'Broccoli'], 'Dairy': ['Milk']}
How it works: The `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 directly without checking if the key exists first. This makes iterating and building grouped collections very concise and avoids `KeyError`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs