PYTHON

Group Dictionary Items by a Common Key Using defaultdict

Discover how to group a list of dictionaries by a specified key using `collections.defaultdict`, perfect for aggregating data like API logs or user activities.

from collections import defaultdict

transactions = [
    {'user_id': 'a1', 'amount': 100, 'item': 'Laptop'},
    {'user_id': 'b2', 'amount': 50, 'item': 'Mouse'},
    {'user_id': 'a1', 'amount': 20, 'item': 'Keyboard'},
    {'user_id': 'c3', 'amount': 150, 'item': 'Monitor'},
    {'user_id': 'b2', 'amount': 30, 'item': 'Webcam'}
]

# Group transactions by user_id
grouped_transactions = defaultdict(list)
for t in transactions:
    grouped_transactions[t['user_id']].append(t)

print(dict(grouped_transactions))
How it works: This code snippet shows how to efficiently group a list of dictionaries based on a common key (`user_id` in this example) using `collections.defaultdict`. The `defaultdict(list)` automatically creates a new empty list as the default value for any new key accessed, simplifying the grouping logic significantly compared to checking for key existence with a regular dictionary. This pattern is highly useful for aggregating related data, such as all transactions belonging to a specific user, or grouping log entries by their source.

Need help integrating this into your project?

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

Hire DigitalCodeLabs