fluttersmith/py-snippetsGitHub ↗

Count items by a key

Count how many items map to each key, using collections.Counter.

Lists#counting#groupingO(n) time✓ 4 examples pass on 3.11–3.14

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)))
  1. 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).

How it works

  • map(key, items) computes the keys lazily.
  • Counter tallies them in one pass. Converting to dict gives a plain result with a predictable repr.

Complexity: O(n) time, O(k) space for k keys

Importfrom 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.