提问者:小点点

通过添加具有相同键值的两个列表创建字典


我有如下两个列表,

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

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

所以最终的字典应该是这样的,

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

我可以使用for循环来实现这一点,但是执行时间会更长,我需要寻找一些python快捷方式来最有效地实现这一点。


共3个答案

匿名用户

您可以使用collections.defaultdict进行并行迭代:

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}

匿名用户

您必须使用zip()函数。 在它中,我们在2个列表中迭代,然后创建一个新的字典键j,它来自L1,并为它赋值i,它来自L2。 如果L1中的键已经在字典键中,它的值将按需要添加。

l1=['a', 'b', 'c', 'c', 'a','a','d','b']
l2=[2, 4, 6, 8, 10, 12, 14, 16]
output = {}
for j, i in zip(l1, l2):
    if j in output.keys():
        output[j] = output[j] + i
    else:
        output[j] = i
print(output)

匿名用户

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}