[英]Python - create dictionary from two lists with repeated elements
尝试使用 zip() 从两个列表(键和值)创建一个字典,其中有一个重复的键元素。 我想要的是字典有一个重复元素的键,并且对应的值是重复值的总和。
lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = dict(zip(lst1,lst2))
print(new_dictionary)
实际 output: {'a': 2, 'b': 6, 'c': 4, 'd': 5}
所需的 output: {'a': 2, 'b': 9, 'c': 4, 'd': 5}
如果您使用defaultdict
,则可以将类型设置为int
。 这将让您简单地添加它:
from collections import defaultdict
new_dictionary = defaultdict(int)
lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
for k, n in zip(lst1,lst2):
new_dictionary[k] += n
print(new_dictionary)
# defaultdict(<class 'int'>, {'a': 2, 'b': 9, 'c': 4, 'd': 5})
您也可以通过简单地使用new_dictionary = Counter()
collections.Counter()
以相同的方式使用 collections.Counter() 。
这里有一个方法:
lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = {}
for key, value in zip(lst1, lst2):
if key in new_dictionary:
new_dictionary[key] += value
else:
new_dictionary[key] = value
print(new_dictionary)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.