← Back to all snippets
PYTHON

Group List Items Using `collections.defaultdict`

Efficiently group elements from a list of dictionaries or objects by a common key in Python using `collections.defaultdict`, perfect for data aggregation in web apps.

from collections import defaultdict

data = [
    {'name': 'Alice', 'city': 'New York'},
    {'name': 'Bob', 'city': 'London'},
    {'name': 'Charlie', 'city': 'New York'},
    {'name': 'David', 'city': 'Paris'},
    {'name': 'Eve', 'city': 'London'},
]

# Group people by city
grouped_by_city = defaultdict(list)
for item in data:
    grouped_by_city[item['city']].append(item['name'])

print(f"Grouped by city: {dict(grouped_by_city)}")

# Count items by category
products = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
category_counts = defaultdict(int)
for product in products:
    category_counts[product] += 1

print(f"Category counts: {dict(category_counts)}")
How it works: `collections.defaultdict` simplifies grouping and counting tasks by providing a default value for a new key when accessed. Instead of checking if a key exists before appending an item or incrementing a count, you can directly use `defaultdict`. If the key is not present, it automatically creates an entry with the specified default factory (e.g., `list` for grouping, `int` for counting), making the code cleaner and less prone to `KeyError` exceptions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs