PYTHON
Group Items by Key in a List of Python Dictionaries
Master grouping a list of dictionaries by a common key into a new dictionary where keys are the grouping criteria and values are lists of matching dictionaries, using `collections.defaultdict`.
from collections import defaultdict
def group_by_key(data_list, key_name):
grouped_data = defaultdict(list)
for item in data_list:
key_value = item.get(key_name)
if key_value is not None: # Only group if key exists and has a value
grouped_data[key_value].append(item)
return dict(grouped_data) # Convert back to a regular dict if preferred
users = [
{'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': 'Paris'},
{'id': 5, 'name': 'Eve', 'city': 'London'},
]
grouped_by_city = group_by_key(users, 'city')
print("Grouped by city:")
for city, user_list in grouped_by_city.items():
print(f" {city}: {user_list}")
products = [
{'product_id': 'P001', 'name': 'Laptop', 'category': 'Electronics'},
{'product_id': 'P002', 'name': 'Mouse', 'category': 'Electronics'},
{'product_id': 'P003', 'name': 'Shirt', 'category': 'Apparel'},
{'product_id': 'P004', 'name': 'Keyboard', 'category': 'Electronics'},
{'product_id': 'P005', 'name': 'Jeans', 'category': 'Apparel'},
]
grouped_by_category = group_by_key(products, 'category')
print("
Grouped by category:")
for category, product_list in grouped_by_category.items():
print(f" {category}: {product_list}")
How it works: This snippet demonstrates how to group a list of dictionaries based on the value of a specific key within each dictionary. It uses `collections.defaultdict(list)`, which automatically initializes a new empty list for a key the first time it's accessed, simplifying the grouping logic significantly. This pattern is extremely useful in web development when processing data retrieved from a database or an API, allowing you to easily organize and present related items, for example, grouping products by category, users by country, or articles by author.