How to Group a List of Dictionaries by Key in Python
Group a list of dictionaries by a specified key field using dict.setdefault to build a dictionary of lists.
Python code
17 linesdef group_by_key(records, key):
grouped = {}
for record in records:
grouped.setdefault(record[key], []).append(record)
return grouped
if __name__ == "__main__":
data = [
{"name": "Alice", "dept": "engineering"},
{"name": "Bob", "dept": "sales"},
{"name": "Carol", "dept": "engineering"},
{"name": "Dave", "dept": "sales"},
{"name": "Eve", "dept": "engineering"},
]
result = group_by_key(data, "dept")
for dept, people in result.items():
print(f"{dept}: {[p['name'] for p in people]}")
Output
engineering: ['Alice', 'Carol', 'Eve']
sales: ['Bob', 'Dave']
How it works
The group_by_key function iterates over each record and uses setdefault on the grouping key. setdefault(key, []) returns the existing list if the key is present, otherwise inserts an empty list and returns it — so records always append to a valid list. This avoids the common pattern of checking if key in grouped and explicitly initializing the list. The result is a dictionary where each key maps to a list of all dictionaries sharing that key value. This approach is efficient because setdefault performs a single lookup instead of separate get/set operations.
Common mistakes
- Using `grouped[record[key]].append(record)` without initializing the list first, which raises KeyError
- Forgetting that the grouping key must exist in every record — missing keys will raise a KeyError
- Mutating the grouped dictionary while iterating over the source list, which can cause confusing behavior
Variations
- Use `collections.defaultdict(list)` to automatically create lists for new keys
- Use a dictionary comprehension with `itertools.groupby` if the input is already sorted by the grouping key
Real-world use cases
- Partitioning API response records by status code to handle successes and failures separately.
- Grouping log entries by severity level before writing them to distinct output streams.
- Organizing customer orders by region in a reporting pipeline for per-region analytics.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.