Python

group_by — Group Items by a Key

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A dict-returning groupby that doesn't require sorted input. Like itertools.groupby but materializes the groups so consumers can iterate them multiple times.
Python
Raw
from collections import defaultdict
from typing import Callable, Iterable, TypeVar

T = TypeVar("T")
K = TypeVar("K")

def group_by(items: Iterable[T], key: Callable[[T], K]) -> dict[K, list[T]]:
    out: dict[K, list[T]] = defaultdict(list)
    for item in items:
        out[key(item)].append(item)
    return dict(out)

users = [
    {"name": "Alice", "team": "A"},
    {"name": "Bob",   "team": "B"},
    {"name": "Cara",  "team": "A"},
]
print(group_by(users, key=lambda u: u["team"]))
# {'A': [Alice, Cara], 'B': [Bob]}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.