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

Viewed 35

When the value of dict_two appears in dict_one, I would like to add the corresponding values, storing them in dict_one, in a Pythonic way, if possible.

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)
1 Answers

You can use dict comprehension like this:

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

This returns:

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

Or if you prefer to update dict_one in-place:

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