Group records and invert a dictionary
Group with setdefault or defaultdict(list) — one pass, one lookup per record, no scanning for an existing group. Inverting is a one-line comprehension, with two traps: duplicate values silently collapse, and unhashable values raise.
Overview
Three ways to group
setdefault(key, []).append(x) — no import, and it makes the default explicit. It does construct an empty list on every call, which is why the next form is usually preferred.
defaultdict(list) — the idiomatic answer. Remember that reading a missing key creates it, so it is not safe to inspect casually.
itertools.groupby — the one that catches people. It groups consecutive equal keys only, so it needs the input sorted by the same key first. It is not the SQL GROUP BY its name suggests.
Step through it
What to watch
- Each record costs one lookup and one append.
- Groups appear as they are first encountered.
- Inversion assumes the values are unique — watch what happens when they are not.
Say this out loud
"defaultdict(list) and append - one pass, O(n). For inverting, a dict comprehension, but I'd check the values are unique first, because duplicates silently overwrite and you lose entries without an error."