PYTHON
Group Objects by a Common Attribute Using dict.setdefault
Learn to group a list of objects or dictionaries by a specific attribute or key using Python's `dict.setdefault`, a powerful technique for data organization.
from collections import namedtuple
# Define a simple data structure for demonstration
Product = namedtuple('Product', ['id', 'name', 'category', 'price'])
products = [
Product(1, 'Laptop', 'Electronics', 1200),
Product(2, 'Mouse', 'Electronics', 25),
Product(3, 'Keyboard', 'Electronics', 75),
Product(4, 'T-Shirt', 'Apparel', 20),
Product(5, 'Jeans', 'Apparel', 60),
Product(6, 'Desk Lamp', 'Home & Office', 40)
]
# Group products by 'category' using dict.setdefault()
products_by_category = {}
for product in products:
# setdefault returns the value for key if key is in dictionary,
# else inserts key with a value of default and returns default.
# Here, default is an empty list if category doesn't exist yet.
products_by_category.setdefault(product.category, []).append(product)
print("Products grouped by category:")
for category, items in products_by_category.items():
print(f"
Category: {category}")
for item in items:
print(f" - {item.name} (${item.price})")
# Example with a list of dictionaries:
users = [
{'id': 1, 'name': 'Alice', 'role': 'admin'},
{'id': 2, 'name': 'Bob', 'role': 'editor'},
{'id': 3, 'name': 'Charlie', 'role': 'admin'},
{'id': 4, 'name': 'David', 'role': 'viewer'}
]
users_by_role = {}
for user in users:
users_by_role.setdefault(user['role'], []).append(user)
print("
Users grouped by role:")
for role, user_list in users_by_role.items():
print(f"
Role: {role}")
for user in user_list:
print(f" - {user['name']}")
How it works: This snippet demonstrates how to group a list of objects (or dictionaries) by a common attribute using the `dict.setdefault()` method. For each item, `setdefault()` checks if the attribute's value (e.g., 'Electronics' for 'category') exists as a key in the `products_by_category` dictionary. If not, it creates that key with an empty list as its value and then returns that list. If the key already exists, it simply returns the existing list. In both cases, the current item is then appended to the returned list, effectively grouping all items sharing the same attribute value.