PYTHON

Efficiently Group Items by a Key Using defaultdict

Learn to group a list of dictionaries or objects by a common key using Python's collections.defaultdict for cleaner, more concise code than traditional dictionary checks.

from collections import defaultdict

# Sample data
data = [
    {'name': 'Alice', 'category': 'A'},
    {'name': 'Bob', 'category': 'B'},
    {'name': 'Charlie', 'category': 'A'},
    {'name': 'David', 'category': 'C'},
    {'name': 'Eve', 'category': 'B'},
]

# Group items by 'category'
grouped_data = defaultdict(list)
for item in data:
    grouped_data[item['category']].append(item['name'])

print(dict(grouped_data))

# Example output:
# {'A': ['Alice', 'Charlie'], 'B': ['Bob', 'Eve'], 'C': ['David']}
How it works: This snippet demonstrates how to efficiently group elements from a list of dictionaries based on a specific key using `collections.defaultdict`. Instead of checking if a key exists in a dictionary before appending, `defaultdict(list)` automatically initializes a new list for a key if it doesn't already exist, simplifying the grouping logic and making the code cleaner and more concise.

Need help integrating this into your project?

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

Hire DigitalCodeLabs