Python-从两个包含重复元素的列表创建字典

Python-从两个包含重复元素的列表创建字典,python,dictionary,zip,Python,Dictionary,Zip,尝试使用zip()从两个列表(键和值)创建字典,其中有重复的键元素。我想要的是,字典对重复元素有一个键,对应的值是重复值的总和 lst1 = ['a', 'b', 'c', 'd', 'b'] lst2 = [2, 3, 4, 5, 6] new_dictionary = dict(zip(lst1,lst2)) print(new_dictionary) 实际输出:{'a':2,'b':6,'c':4,'d':5} 所需输出:{'a':2'b':9'c':4'd':5}以下是一种方法: ls

尝试使用zip()从两个列表(键和值)创建字典,其中有重复的键元素。我想要的是,字典对重复元素有一个键,对应的值是重复值的总和

lst1 = ['a', 'b', 'c', 'd', 'b']
lst2 = [2, 3, 4, 5, 6]
new_dictionary = dict(zip(lst1,lst2))
print(new_dictionary)
实际输出:
{'a':2,'b':6,'c':4,'d':5}

所需输出:
{'a':2'b':9'c':4'd':5}

以下是一种方法:

lst1=['a','b','c','d','b']
lst2=[2,3,4,5,6]
新字典={}
对于键,zip中的值(lst1,lst2):
如果输入新字典:
新字典[键]+=值
其他:
新字典[键]=值
打印(新字典)

如果使用
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})
从集合导入defaultdict
新字典=defaultdict(int)
lst1=['a','b','c','d','b']
lst2=[2,3,4,5,6]
对于zip中的k,n(lst1,lst2):
新字典[k]+=n
打印(新字典)
#defaultdict(,{'a':2,'b':9,'c':4,'d':5})

您也可以使用
collections.Counter()
,方法与使用
new\u dictionary=Counter()
相同。

这是否回答了您的问题?