PYTHON
Grouping Items into a Dictionary of Lists using defaultdict
Learn to efficiently group a list of dictionaries or objects by a specific key into a dictionary where values are lists, using Python's `collections.defaultdict` for cleaner code.
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 data by 'city'
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item['city']].append(item['name'])
print(dict(grouped_by_city))
# Expected output:
# {
# 'New York': ['Alice', 'Charlie'],
# 'London': ['Bob', 'Eve'],
# 'Paris': ['David']
# }
How it works: This snippet demonstrates using `collections.defaultdict` to group items efficiently. When you try to access a key that doesn't exist in a `defaultdict`, it automatically creates a new value using the provided factory function (here, `list`). This eliminates the need to check if a key exists before appending an item, resulting in cleaner and more concise code for common grouping tasks in web development, such as organizing query results or API data.