How do I collapse elements in Python?

For instance:

l = [('a',1),('b',2),('a',2)]

collapsed_l = dict(a=[1,2],b=[2])

What is the best way to get from lto collapsed_l?

In a sense, I want to somehow generalize which “field” I am collapsing and in which field. I think this is similar to what pivot tables do in databases and tables, but I could be wrong.

+3
source share
3 answers
>>> from collections import defaultdict
>>> l = [('a',1),('b',2),('a',2)]
>>> collapsed_l = defaultdict(list)     
>>> for letter,num in l:
        collapsed_l[letter].append(num)


>>> collapsed_l
defaultdict(<type 'list'>, {'a': [1, 2], 'b': [2]})
+5
source
>>> 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 the order of the collapsed values ​​matters, so you can edit sorted(l)tosorted(l,key=itemgetter(0))

+5
source

- . Setdefault , , . , .

>>> d=dict()
>>> for k,e in l:
    d.setdefault(k,[]).append(e)        
>>> d
{'a': [1, 2], 'b': [2]}

collections.defaultdict , setdefault.

+2

All Articles