我如何从元组列表中创建字典?

时间:2014-11-02 21:02:44

标签: python list dictionary

我如何从这样的列表中创建字典:

list = [('a', [10,3]), ('a', [30,20]), ('b', [96,45]), ('b', [4,20])]

我想要的结果是:

dict = { 'a':[10,3,30,20], 'b':[96,45,4,20] }

2 个答案:

答案 0 :(得分:5)

您可以使用collections.defaultdict

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

或者,如果您想避免导入,请尝试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]}
>>>

答案 1 :(得分:1)

这也有效:(它假设您的商品已按键排序。如果没有,则只使用sortedi(items)代替)

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