Here is a clean and idiomatic way to group a list of dictionaries using Python's built-in collections.defaultdict.
The Function
from collections import defaultdict
from typing import Any, Dict, List, Hashable
def group_by_key(items: List[Dict[str, Any]], key: str) -> Dict[Hashable, List[Dict[str, Any]]]:
"""
Groups a list of dictionaries by a specified key.
:param items: List of dictionaries to group.
:param key: The dictionary key to group by.
:return: A dictionary where each key maps to a list of matching dicts.
"""
grouped = defaultdict(list)
for item in items:
if key in item:
grouped[item[key]].append(item)
return dict(grouped)
Example Usage
# Sample data
users = [
{"name": "Alice", "role": "Admin"},
{"name": "Bob", "role": "Member"},
{"name": "Charlie", "role": "Admin"},
{"name": "Diana", "role": "Guest"},
]
# Group by the 'role' key
result = group_by_key(users, "role")
print(result)
Output:
{
"Admin": [
{"name": "Alice", "role": "Admin"},
{"name": "Charlie", "role": "Admin"}
],
"Member": [
{"name": "Bob", "role": "Member"}
],
"Guest": [
{"name": "Diana", "role": "Guest"}
]
}
Key Highlights
- Performance: Runs in $O(N)$ time complexity with a single pass over the list.
- Safe: Uses
if key in item to gracefully skip entries where the grouping key does not exist.
- Clean return: Converts
defaultdict back to a standard dict at the end to prevent unexpected behavior downstream.