PYTHON
Group List of Objects by Attribute using defaultdict
Learn to efficiently group Python objects in a list into categories based on a common attribute using `collections.defaultdict`, perfect for data aggregation.
from collections import defaultdict
class Product:
def __init__(self, name, category, price):
self.name = name
self.category = category
self.price = price
def __repr__(self):
return f"Product(name='{self.name}', category='{self.category}', price={self.price})"
products = [
Product("Laptop", "Electronics", 1200),
Product("Mouse", "Electronics", 25),
Product("Keyboard", "Electronics", 75),
Product("T-Shirt", "Apparel", 20),
Product("Jeans", "Apparel", 60),
Product("Book", "Books", 15),
Product("E-Reader", "Electronics", 150)
]
# Group products by their category
grouped_products = defaultdict(list)
for product in products:
grouped_products[product.category].append(product)
print("Grouped Products by Category:")
for category, items in grouped_products.items():
print(f"- {category}:")
for item in items:
print(f" {item.name} (${item.price})")
How it works: This snippet demonstrates how to group a list of objects based on one of their attributes using `collections.defaultdict(list)`. Instead of checking if a key exists before appending, `defaultdict` automatically creates an empty list as the default value for a new key, simplifying the grouping logic. This pattern is highly efficient and Pythonic for categorizing data, common in scenarios like organizing products by category or users by their role.