从两个列表创建字典,并添加具有相同键的值

时间:2020-07-19 14:36:00

标签: python list dictionary

我有两个类似下面的列表,

l1=['a', 'b', 'c', 'c', 'a','a','d','b']
l2=[2, 4, 6, 8, 10, 12, 14, 16]

现在想从上面的列表中创建字典,例如-键在l1中是唯一的,而l2中的值将被添加,

所以最终的字典看起来像

d={'a':24, 'b':20, 'c': 14, 'd':14}

我可以使用for循环来执行此操作,但是执行时间会更多,需要一些python快捷方式来最有效地执行此操作。

4 个答案:

答案 0 :(得分:2)

为此,您可以将collections.defaultdictzip一起使用,以并行地进行迭代:

from collections import defaultdict

l1 = ['a', 'b', 'c', 'c', 'a','a','d','b']
l2 = [2, 4, 6, 8, 10, 12, 14, 16]

d = defaultdict(int)
for k, v in zip(l1, l2):
    d[k] += v

print(d)
# {'a': 24, 'b': 20, 'c': 14, 'd': 14}

答案 1 :(得分:1)

具有理解力:

from  more_itertools import unique_everseen
d = {i: sum([l2[x] for x in [y for y,val in enumerate(l1) if val==i]]) for i in  list(unique_everseen(l1))}

输出:

{'a':24, 'b':20, 'c': 14, 'd':14}

答案 2 :(得分:0)

您必须使用zip()函数。在其中,我们在2个列表中进行迭代,然后创建一个来自j的新字典键l1并为其分配一个值,i来自{{1} }。如果l2中的键已经在字典键中,则将按需要添加它的值。

l1

答案 3 :(得分:0)

l1 = ['a', 'b', 'c', 'c', 'a','a','d','b']
l2 = [2, 4, 6, 8, 10, 12, 14, 16]    

idx = 0
d = {}
for v in l1:
  d[v] = d.get(v, 0) + l2[idx]
  idx += 1

print d
# {'a': 24, 'b': 20, 'c': 14, 'd': 14}