2017-08-26 17 views
0

]我正在创建一个函数来创建一个新的库,用于将来自库项目的重复值[a]与来自库项目[b]的值的总和。另外,对于给定的长度n,将0指定给未指定的密钥。创建一个新的库[b],从库[a]与来自库[a]的总和值配对的重复键[

例如d = {A:[1,2,2,5],B:[3,2,2,1]}

返回d = {1:3,2:4,3 :0,4:0,5:1}

有没有人有想法解决这个问题使用set()或defaultdict()?

谢谢。

我目前的进度:

from collections import defaultdict 
d = {} 
d['a'] = [1, 2, 2, 5] 
d['b'] = [3,2,2,1] 
x = list(zip(d['a'],d['b'])) 
output = defaultdict(int) 
for a,b in x: 
output[a]+=b 
x = dict(output) 
x = dict(output) 
sorted_x = sorted(x.items(), key=lambda x: x[0]) 

print (sorted_x) 
n= 8 
y = dict(sorted_x) 
for i, j in dict(sorted_x).items(): 
for a in range (n):......... 

但是,我不知道到y中分配新对

+0

Python或C++? –

+0

对不起。我正在使用python3 – derec

回答

0

Python不支持字典重复键。

如果定义词典像d = {1:1,4:2,1:3},

然后Python将只保留一个像d唯一密钥= {1:3 ,4:2}

我想你可以使用下面的方法:

from collections import defaultdict 
d=[(1,1),(4,2),(1,3)] # Use List of tuples to stores all the duplicate keys 
output = defaultdict(int) 
for k,v in d: 
    output[k]+=v 
print output 
相关问题