pysnippets.lists.count_by
Count items by a key
count_by(items: Iterable[T], key: Callable[[T], K]) -> dict[K, int]
Count how many items map to each key, using collections.Counter.
Like group_by, but when you only need the size of each group.
count_by.py✓ ruff · mypy --strict
from collections import Counter
from collections.abc import Callable, Hashable, Iterable
from typing import TypeVar
T = TypeVar("T")
K = TypeVar("K", bound=Hashable)
def count_by(items: Iterable[T], key: Callable[[T], K]) -> dict[K, int]:
"""Count ``items`` by the result of ``key``."""
return dict(Counter(map(key, items)))- Counter does the counting; map applies key lazily
examples✓ 4 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> from math import floorpassed on Python 3.11 to 3.14: >>> count_by([6.1, 4.2, 6.3], floor){6: 2, 4: 1}passed on Python 3.11 to 3.14: >>> count_by(["one", "two", "three"], len){3: 2, 5: 1}passed on Python 3.11 to 3.14: >>> count_by([], len){}Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
map(key, items)computes the keys lazily.Countertallies them in one pass. Converting todictgives a plain result with a predictable repr.
Complexity: O(n) time, O(k) space for k keys
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.lists.count_by import count_byNo dependencies: copy count_by.py into your project, or clone the repo.Adapted from count-by in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten with Counter; key is required and typed. Suggest an edit.