PYTHON

Group List of Dictionaries by Key

Learn to efficiently group a list of dictionaries or objects by a common key into a dictionary of lists using Python's collections.defaultdict, perfect for data aggregation.

from collections import defaultdict

data = [
    {'id': 1, 'category': 'fruit', 'name': 'apple'},
    {'id': 2, 'category': 'vegetable', 'name': 'carrot'},
    {'id': 3, 'category': 'fruit', 'name': 'banana'},
    {'id': 4, 'category': 'dairy', 'name': 'milk'},
    {'id': 5, 'category': 'vegetable', 'name': 'broccoli'},
]

grouped_by_category = defaultdict(list)
for item in data:
    grouped_by_category[item['category']].append(item)

print(f"Original data:
{data}")
print(f"
Grouped by category:
{dict(grouped_by_category)}")

# Example of accessing a specific group
print(f"
Fruits: {grouped_by_category['fruit']}")
How it works: When you need to group items from an iterable (like a list of dictionaries) based on a specific key, `collections.defaultdict` is incredibly useful. Instead of checking if a key exists before appending an item (which would require boilerplate `if key not in dict: dict[key] = []`), `defaultdict(list)` automatically initializes a new empty list for a key the first time it's accessed, allowing direct `append()` operations and simplifying the grouping logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs