← Back to all snippets
PYTHON

Group a List of Dictionaries by a Common Key

Learn to efficiently group items in a Python list of dictionaries into a dictionary of lists using collections.defaultdict for organized data processing.

from collections import defaultdict

data = [
    {"id": 1, "category": "fruits", "name": "apple"},
    {"id": 2, "category": "vegetables", "name": "carrot"},
    {"id": 3, "category": "fruits", "name": "banana"},
    {"id": 4, "category": "dairy", "name": "milk"},
    {"id": 5, "category": "vegetables", "name": "broccoli"}
]

def group_by_key(items, key_name):
    grouped_data = defaultdict(list)
    for item in items:
        grouped_data[item[key_name]].append(item)
    return dict(grouped_data) # Convert defaultdict to regular dict for final output

grouped_items = group_by_key(data, "category")
print(grouped_items)
# Expected output format (order might vary):
# {
#   'fruits': [
#     {'id': 1, 'category': 'fruits', 'name': 'apple'},
#     {'id': 3, 'category': 'fruits', 'name': 'banana'}
#   ],
#   'vegetables': [
#     {'id': 2, 'category': 'vegetables', 'name': 'carrot'},
#     {'id': 5, 'category': 'vegetables', 'name': 'broccoli'}
#   ],
#   'dairy': [
#     {'id': 4, 'category': 'dairy', 'name': 'milk'}
#   ]
# }
How it works: This snippet demonstrates how to group a list of dictionaries based on a specific key's value using `collections.defaultdict`. The `defaultdict` is initialized with `list` as its default factory, meaning if a key is accessed for the first time, a new empty list is automatically created for it. This simplifies the grouping logic by removing the need to explicitly check if a key already exists before appending an item. The final result is converted to a regular dictionary for a standard output format.

Need help integrating this into your project?

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

Hire DigitalCodeLabs