我有以下两个词典
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的分数并制作新词典
OR
2。更新score2词典(并将score1中的值添加到score2对应的各个值
一个公认的答案会显示上述任何合适的解释,并建议更精确或有效的方法来解决问题。
有人建议另一个SO答案可以简单地添加词典:
打印(scores1 + scores2) 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 :(得分:1)
对于第一个解决方案:
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}