src/graphql/pyutils/group_by.py
raw| 1 | from collections import defaultdict |
| 2 | from typing import Callable, Collection, Dict, List, TypeVar |
| 3 | |
| 4 | __all__ = ["group_by"] |
| 5 | |
| 6 | K = TypeVar("K") |
| 7 | T = TypeVar("T") |
| 8 | |
| 9 | |
| 10 | def group_by(items: Collection[T], key_fn: Callable[[T], K]) -> Dict[K, List[T]]: |
| 11 | """Group an unsorted collection of items by a key derived via a function.""" |
| 12 | result: Dict[K, List[T]] = defaultdict(list) |
| 13 | for item in items: |
| 14 | key = key_fn(item) |
| 15 | result[key].append(item) |
| 16 | return result |