Group items by key in Python
SQL's GROUP BY, in three lines of Python.
from collections import defaultdict
def group_by(items, key):
groups = defaultdict(list)
for item in items:
groups[key(item)].append(item)
return dict(groups)
How it works
defaultdict(list)creates a bucket the first time a key appears.- Each item lands in the bucket its key function picks.
- Returns the groups as a plain dict.
Keywords and builtins used here
defdictforgroup_bylistreturn
The run, in numbers
- Lines
- 7
- Characters to type
- 159
- Tokens
- 40
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 24 seconds.
Step 10 of 10 in Collections, step 32 of 72 in Language basics.