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

2024-09-30 12:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两本字典

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

Tags: 方法答案infordictionary字典updatekeys
1条回答
网友
1楼 · 发布于 2024-09-30 12:27:04

对于第一个解决方案:

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}

相关问题 更多 >

    热门问题