PYTHON
Group List of Dictionaries by a Common Key
Discover how to group a list of Python dictionaries into a new dictionary where keys are derived from a common attribute. Ideal for categorizing data in web development.
products = [
{'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200},
{'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75},
{'id': 3, 'name': 'Chair', 'category': 'Furniture', 'price': 300},
{'id': 4, 'name': 'Monitor', 'category': 'Electronics', 'price': 400},
{'id': 5, 'name': 'Desk', 'category': 'Furniture', 'price': 250}
]
# Group products by their 'category'
grouped_products = {}
for product in products:
category = product['category']
if category not in grouped_products:
grouped_products[category] = []
grouped_products[category].append(product)
print(f"Grouped Products by Category:
{grouped_products}")
# Example usage: Accessing products in a specific category
print(f"
Electronics Products: {grouped_products.get('Electronics', [])}")
print(f"Furniture Products: {grouped_products.get('Furniture', [])}")
How it works: This snippet shows a common pattern in web development: grouping a list of dictionaries based on the value of a specific key. Here, a list of product dictionaries is grouped by their 'category'. The code iterates through the list, and for each item, it checks if its category already exists as a key in the `grouped_products` dictionary. If not, a new list is initialized for that category; then, the current product is appended to the corresponding category's list. This technique is fundamental for organizing and presenting data, such as displaying products categorized on an e-commerce site or organizing data for reports.