Group items by a key
Collect a list of records into a dictionary of lists keyed by a field or function result.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
from collections import defaultdict
def group_by(items, key):
groups = defaultdict(list)
for item in items:
groups[key(item)].append(item)
return dict(groups)Example / expected output
group_by(["apple", "avocado", "banana"], key=lambda s: s[0])
# {'a': ['apple', 'avocado'], 'b': ['banana']}How it works
defaultdict(list) removes the need to check whether a key exists. The key can be any callable, so the same helper groups by field, by first letter, by computed bucket and so on. Order within each group is the input order.
Related snippets
- Python Tested
Safely read a deeply nested value
Walk a path through nested dicts and lists and return a default instead of raising KeyError.
- Python Tested
Flatten a nested dictionary
Turn nested dicts into a single-level dict with dotted keys, handy for config and logging.
- Python Tested
Flatten a nested list
Flatten arbitrarily nested lists and tuples into a single flat iterator, leaving strings intact.
- Python Tested
Remove duplicates but keep order
Deduplicate a list while preserving the first occurrence order, for hashable values or by key.

