Skip to content
GreenSnippets

Group items by a key

Collect a list of records into a dictionary of lists keyed by a field or function result.

Python
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

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.