添加两个不同字典中的值并创建一个新字典

Adding the values in a two different dictionaries and creating a new dictionary

我有以下两本词典

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 的分数进行整理和求和,以生成以下输出:

答案可能是 'done' 使用以下两种方法之一(可能还有其他我有兴趣听到的方法)

1.使用创建新字典:

finalscores={a:30,b:30} #将键 a 和 b 的分数相加并创建一个新字典

2。更新 scores2 字典(并将 scores1 中的值添加到 scores2 对应的相应值

一个被接受的答案将显示以上内容以及任何合适的解释,并提出任何更精明或更有效的解决问题的方法。

关于另一个 SO 答案的建议是可以简单地添加字典:

打印(分数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

第一个解法:

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

finalscores=dict((key, sum([scores1[key] if key in scores1 else 0, scores2[key] if key in scores2 else 0])) for key in set(scores1.keys()+scores2.keys()))
print(finalscores)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}

这将遍历两个字典中的一组所有键,创建一个元组,其中包含两个字典中键的值 或 0,然后将所述元组传递给 sum函数添加结果。最后,它生成一个字典。

编辑

在多行中,要理解逻辑,这就是单行代码的作用:

finalscores = {}
for key in set(scores1.keys()+scores2.keys()):
    score_sum = 0
    if key in scores1:
        score_sum += scores1[key]
    if key in scores2:
        score_sum += scores2[key]
    finalscores[key] = score_sum

第二种解法:

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

for k1 in scores1:
    if k1 in scores2:
        scores2[k1] += scores1[k1]  # Adds scores1[k1] to scores2[k1], equivalent to do scores2[k1] = scores2[k1] + scores1[k1]
    else:
        scores2[k1] = scores1[k1]

print(scores2)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}