Converting a list of tuples into a dict
l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
d = {}
for x, y in l:
d.setdefault(x, []).append(y)
print d
produces:
{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
A solution using groupby
from itertools import groupby
l = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),]
[(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])]
Output:
[('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])]
groupby(l, lambda x:x[0])
gives you an iterator that contains
['a', [('a', 1), ...], c, [('c', 1)], ...]
Slightly simpler...
from collections import defaultdict
fq = defaultdict(list)
for n, v in myList:
fq[n].append(v)
print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})