Python 3- 如何将一个字典中的键与另一个字典进行比较,将它们的值相加,并将结果存储在第一个字典的值中?

Python 3- How do I compare keys in one dictionary to another, add their values, storing the result in the value of the first?

dict_two的值出现在dict_one时,我想添加相应的值,如果可能的话,以Pythonic的方式将它们存储在dict_one中。

dict_one = {'rose':5,
            'daisy':5,
            'lily':5,
            'anthurium':5,
            'sunflower':5}

dict_two = {'rose':1,
            'lily':2,
            'sunflower':5}

for i in dict_two:
    if i in dict_two.keys():
        dict_one[i] += dict_two[i]

print(dict_one)

你可以像这样使用字典理解:

{k: v + dict_two.get(k, 0) for k, v in dict_one.items()}

这个returns:

{'rose': 6, 'daisy': 5, 'lily': 7, 'anthurium': 5, 'sunflower': 10}

或者,如果您希望就地更新 dict_one

dict_one.update({k: v + dict_one[k] for k, v in dict_two.items() if k in dict_one})