← All tips

Python: `defaultdict` for grouped data

pythonstdlib

Useful for grouping items by a key.

from collections import defaultdict
m = defaultdict(list)
for k,v in [('a',1),('a',2)]:
    m[k].append(v)
print(m['a'])