PYTHON
Grouping Dictionaries (Objects) by a Specific Key
Group a list of dictionaries into a new dictionary where items are organized by a common key, useful for processing structured API responses.
def group_by_key(list_of_dicts, key_to_group_by):
grouped_data = {}
for item in list_of_dicts:
key_value = item.get(key_to_group_by)
if key_value is not None:
if key_value not in grouped_data:
grouped_data[key_value] = []
grouped_data[key_value].append(item)
return grouped_data
# Example usage:
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": "Spinach"}
]
grouped_by_category = group_by_key(data, "category")
print("Grouped by category:")
for category, items in grouped_by_category.items():
print(f" {category}: {items}")
How it works: This snippet provides a function to group a list of dictionaries based on the value of a specified key. It iterates through the list, extracts the grouping key's value, and uses it to organize items into a new dictionary. The `get()` method is used for safely retrieving the key's value, and each key in the `grouped_data` dictionary will hold a list of all dictionaries that share that key value. This is highly useful for categorizing and processing structured data from APIs or databases.