For example:
l = [('a',1),('b',2),('a',2)]
collapsed_l = dict(a=[1,2],b=[2])
How best to get from l to collapsed_l?
In a sense, I want some way of generalising what "field" I'm collapsing, and by which field. I think this is similar to what pivot tables do in databases and spreadsheets, but I may be wrong.
>>> from itertools import groupby
>>> from operator import itemgetter
>>> l = [('a',1),('b',2),('a',2)]
>>> dict((k,[n for l,n in v]) for k,v in groupby(sorted(l),itemgetter(0)))
{'a': [1, 2], 'b': [2]}
Not sure if order of the collapsed values matters, if so you can edit sorted(l) to sorted(l,key=itemgetter(0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With