How to make a dictionary from a list of tuples?
2 answers
You can use collections.defaultdict
for this:
>>> from collections import defaultdict
>>> lst = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
>>> dct = defaultdict(list)
>>> for x, y in lst:
... dct[x] += y
...
>>> dct
defaultdict(<class 'list'>, {'a': [10, 3, 30, 20], 'b': [96, 45, 4, 20]})
>>>
Or, if you want to avoid imports, try dict.setdefault
:
>>> lst = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
>>> dct = {}
>>> for x, y in lst:
... dct.setdefault(x, []).extend(y)
...
>>> dct
{'a': [10, 3, 30, 20], 'b': [96, 45, 4, 20]}
>>>
+5
source to share
This also works: (assumes your items are already sorted by key. If not, then just use sortedi(items)
instead)
from itertools import groupby
from operator import itemgetter
items = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]
d = dict((key, sum((list_ for _key, list_ in group), []))
# for each group create a key, value tuple. with the value being the
# concatenation of all the lists in the group. eg. [10, 3] + [30, 20]
for key, group in groupby(items, itemgetter(0)))
# group elements in items by the first item in each element
+1
source to share