PYTHON

Group Items by Key with collections.defaultdict

Learn to efficiently group a list of dictionaries or objects by a specific key using Python's collections.defaultdict, perfect for organizing data in web applications.

from collections import defaultdict

# Example data: a list of user activity records
activity_logs = [
    {"user_id": 1, "action": "login", "timestamp": "2023-01-01T10:00:00Z"},
    {"user_id": 2, "action": "view_page", "timestamp": "2023-01-01T10:05:00Z"},
    {"user_id": 1, "action": "logout", "timestamp": "2023-01-01T10:30:00Z"},
    {"user_id": 3, "action": "login", "timestamp": "2023-01-01T11:00:00Z"},
    {"user_id": 2, "action": "add_to_cart", "timestamp": "2023-01-01T11:15:00Z"},
]

# Group activities by user_id
grouped_activities = defaultdict(list)
for log in activity_logs:
    grouped_activities[log["user_id"]].append(log)

# Print the grouped data
for user_id, activities in grouped_activities.items():
    print(f"User ID {user_id}:")
    for activity in activities:
        print(f"  - {activity['action']} at {activity['timestamp']}")

# Example output:
# User ID 1:
#   - login at 2023-01-01T10:00:00Z
#   - logout at 2023-01-01T10:30:00Z
# User ID 2:
#   - view_page at 2023-01-01T10:05:00Z
#   - add_to_cart at 2023-01-01T11:15:00Z
# User ID 3:
#   - login at 2023-01-01T11:00:00Z
How it works: The `collections.defaultdict` is a subclass of the built-in `dict` type that provides a default value for a nonexistent key. When you access a key that hasn't been set yet, `defaultdict` automatically calls the factory function (in this case, `list`) to create a default value (an empty list) and inserts it. This simplifies grouping data by avoiding explicit checks for key existence, making the code cleaner and more concise for tasks like aggregating related records from a database query or API response.

Need help integrating this into your project?

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

Hire DigitalCodeLabs