PYTHON
Group List of Dictionaries by Key Without `defaultdict`
Discover how to group a list of dictionaries by a common key's value into a dictionary of lists, effectively structuring data for reporting or display without relying on `defaultdict`.
data = [
{'id': 1, 'name': 'Alice', 'city': 'New York'},
{'id': 2, 'name': 'Bob', 'city': 'London'},
{'id': 3, 'name': 'Charlie', 'city': 'New York'},
{'id': 4, 'name': 'David', 'city': 'London'},
{'id': 5, 'name': 'Eve', 'city': 'Paris'}
]
# Method 1: Manual check for key existence
grouped_by_city_manual = {}
for item in data:
city = item['city']
if city not in grouped_by_city_manual:
grouped_by_city_manual[city] = []
grouped_by_city_manual[city].append(item)
print(f"Grouped by city (manual check): {grouped_by_city_manual}")
# Method 2: Using dict.setdefault() for conciseness
grouped_by_city_setdefault = {}
for item in data:
city = item['city']
grouped_by_city_setdefault.setdefault(city, []).append(item)
print(f"Grouped by city (setdefault): {grouped_by_city_setdefault}")
How it works: This snippet demonstrates how to group a list of dictionaries based on a specific key's value into a new dictionary, where each key represents a group and its value is a list of dictionaries belonging to that group. It showcases two approaches: a manual check for key existence (typical dictionary logic) and the more concise `dict.setdefault()` method. Both effectively organize tabular data by a common attribute, useful for report generation or data visualization.