from collections import defaultdict def group_by_category(items): """Groups a list of items by their 'category' field. Args: items (list of dict): A list where each dictionary represents an item and has a 'category' key. Returns: defaultdict: A dictionary where keys are categories and values are lists of items belonging to that category. """ grouped_data = defaultdict(list) # Initialize with list as default factory for item in items: category = item.get('category', 'uncategorized') # Handle missing category gracefully grouped_data[category].append(item) return grouped_data # Example Usage: products = [ {'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200}, {'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75}, {'id': 3, 'name': 'Desk Chair', 'category': 'Furniture', 'price': 250}, {'id': 4, 'name': 'Monitor', 'category': 'Electronics', 'price': 300}, {'id': 5, 'name': 'Table', 'category': 'Furniture', 'price': 150}, {'id': 6, 'name': 'Mouse', 'category': 'Electronics', 'price': 25} ] organized_products = group_by_category(products) # organized_products will be: # defaultdict(, { # 'Electronics': [ # {'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200}, # {'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75}, # {'id': 4, 'name': 'Monitor', 'category': 'Electronics', 'price': 300}, # {'id': 6, 'name': 'Mouse', 'category': 'Electronics', 'price': 25} # ], # 'Furniture': [ # {'id': 3, 'name': 'Desk Chair', 'category': 'Furniture', 'price': 250}, # {'id': 5, 'name': 'Table', 'category': 'Furniture', 'price': 150} # ] # }) print(organized_products['Electronics'])