I often want to bucket an unordered collection in python. itertools.groubpy does the right sort of thing but almost always requires massaging to sort the items first and cat
This has come up several times before -- (1), (2), (3) -- and there's a partition recipe in the itertools recipes, but to my knowledge there's nothing in the standard library.. although I was surprised a few weeks ago by accumulate, so who knows what's lurking there these days? :^)
When I need this behaviour, I use
from collections import defaultdict
def partition(seq, key):
d = defaultdict(list)
for x in seq:
d[key(x)].append(x)
return d
and get on with my day.