PYTHON

Group a List of Dictionaries by a Key

Learn to efficiently group a list of dictionaries into a new dictionary, where keys are values from a specified field and values are lists of corresponding dictionaries, using Python's defaultdict.

from collections import defaultdict

data = [
    {"id": 1, "category": "Fruit", "item": "Apple"},
    {"id": 2, "category": "Vegetable", "item": "Carrot"},
    {"id": 3, "category": "Fruit", "item": "Banana"},
    {"id": 4, "category": "Dairy", "item": "Milk"},
    {"id": 5, "category": "Vegetable", "item": "Broccoli"},
]

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

# Convert defaultdict to a regular dict for final output if needed
final_dict = dict(grouped_data)
print(final_dict)

# Expected output:
# {
#     'Fruit': [{'id': 1, 'category': 'Fruit', 'item': 'Apple'}, {'id': 3, 'category': 'Fruit', 'item': 'Banana'}],
#     'Vegetable': [{'id': 2, 'category': 'Vegetable', 'item': 'Carrot'}, {'id': 5, 'category': 'Vegetable', 'item': 'Broccoli'}],
#     'Dairy': [{'id': 4, 'category': 'Dairy', 'item': 'Milk'}]
# }
How it works: This snippet demonstrates how to group a list of dictionaries based on a common key's value. `collections.defaultdict(list)` is used to automatically create a new list for a category if it doesn't exist, preventing `KeyError`. It iterates through the data, appending each dictionary to the list corresponding to its category key. The result is a dictionary where keys are the categories and values are lists of all items belonging to that category.

Need help integrating this into your project?

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

Hire DigitalCodeLabs