group_by.py 471 B

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