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)
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})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.