Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I collapse elements in Python? [duplicate]

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.

like image 696
cammil Avatar asked Mar 01 '26 01:03

cammil


1 Answers

>>> 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))

like image 125
jamylak Avatar answered Mar 03 '26 13:03

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!