我有以下两本字典
scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
以及
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b
我需要对两个字典中键a和键b的分数进行比较和求和,以产生以下输出:
答案可以用以下两种方法中的一种“完成”(可能还有其他我感兴趣的方法)
1.使用新词典的创建:
finalscores={a:30,b:30}#将a和b键的分数相加,生成一个新词典
或者
2.更新scores2字典(并将scores1中的值添加到scores2中相应的值)
一个公认的答案既能说明上述问题,又能给出适当的解释,同时也能提出更精明或有效的解决问题的方法
有人建议另一个答案可以简单地添加词典:
打印(分数1+分数2) Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
但是我想用最简单的方法来实现,不需要迭代器导入或类
我也试过,但没用:
newdict={}
newdict.update(scores1)
newdict.update(scores2)
for i in scores1.keys():
try:
addition = scores[i] + scores[i]
newdict[i] = addition
except KeyError:
continue
对于第一个解决方案:
它遍历两个字典中的一组所有键,用两个字典中键的值创建一个元组或0,然后通过
sum
函数将所述元组传递,并添加结果。最后,它生成一个字典编辑
在多行中,为了理解逻辑,这是一行所做的:
对于第二种解决方案:
相关问题 更多 >
编程相关推荐