How should I collapse elements in Python?

python, python-2.7

Solution

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

Problem

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.

Original source

Related problems