# Created on savesnippets.com ยท https://savesnippets.com/KwhxJJ5gF87jYS 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]}