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

3

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

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个回答

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

啊,比我快一点点! - anon582847382
哇!那讲得很有道理。还感谢你的快速回答。 - WreCs
小提示:defaultdict 并不完全像 dict - 所以在使用之前,您可能希望将其转换为 dict() - Ben

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接