PYTHON
Group a List of Dictionaries by a Specific Key
Learn to manually group a list of dictionaries based on the value of a specific key into a new dictionary, effectively categorizing your data without `defaultdict`.
transactions = [
{'id': 1, 'category': 'Food', 'amount': 50},
{'id': 2, 'category': 'Travel', 'amount': 120},
{'id': 3, 'category': 'Food', 'amount': 30},
{'id': 4, 'category': 'Utilities', 'amount': 80},
{'id': 5, 'category': 'Travel', 'amount': 70}
]
grouped_transactions = {}
for transaction in transactions:
category = transaction['category']
if category not in grouped_transactions:
grouped_transactions[category] = []
grouped_transactions[category].append(transaction)
print("Grouped Transactions:")
import json
print(json.dumps(grouped_transactions, indent=4))
# Example: Grouping by a non-existent key will create empty lists or raise KeyError if not handled
# If a category might be missing, you might want to use .get()
# for transaction in transactions:
# category = transaction.get('type', 'Uncategorized')
# if category not in grouped_transactions:
# grouped_transactions[category] = []
# grouped_transactions[category].append(transaction)
How it works: This snippet demonstrates how to group a list of dictionaries based on a common key's value. It iterates through the `transactions` list. For each transaction, it extracts the `category`. If this `category` is not yet a key in the `grouped_transactions` dictionary, it initializes an empty list for that category. Then, it appends the current transaction dictionary to the list associated with its category. This results in a dictionary where keys are the categories and values are lists of transactions belonging to that category.