Community Python Snippet

groupby Then Aggregate With defaultdict (Python)

Pure stdlib group-then-aggregate: defaultdict(list) for the grouping pass, then a tiny per-group reducer. The version I reach for before importing pandas, plus the multi-stat variant.

groupby Then Aggregate With defaultdict (Python)

Pure stdlib group-then-aggregate: defaultdict(list) for the grouping pass, then a tiny per-group reducer. The version I reach for before importing pandas, plus the multi-stat variant.

Python
Compiler
3 snippets
py-collections
py-itertools
code-template
elenamuller

By @elenamuller

February 8, 2026

·

Updated May 18, 2026

280 views

6

4.4 (8)

Two passes: the first builds defaultdict(list) keyed by group, the second walks each group and emits whatever aggregate you need. The reason I prefer this over itertools.groupby is that groupby requires the input to be sorted by the key and silently produces broken results otherwise; defaultdict does not care about input order. The from __future__ import annotations at the top is what lets the dict[str, list[dict]] type hint parse on Python 3.8 (the playground's Python). For datasets up to a few hundred thousand rows this is faster than constructing a DataFrame and lets the aggregation logic stay in plain Python.