user3805995 user3805995 - 1 year ago 73
Python Question

Dictionary merge by adding values

Suppose I have two dictionaries

a = {'milk':90, 'coffee':80, 'rice':100, 'Cheese': 70}

b = {'milk':90, 'coffee':80, 'pulses': 100,'Alcohol':750}

I want to merge these two dictionaries by adding value of common elements of the dictionaries which should give resultant as:

c = {'milk':180, 'coffee':160, 'rice':100, 'Cheese':70, 'pulses':100, 'Alcohol':750}

I am trying this at my level , please suggest if anyone have a solution for this.

Answer Source

Use the keys of either dicts and add their value to make the third, so it doesn't matter which items are unique to just one of them. Use the dict.get to fetch the value for each key from both dicts, defaulting to 0 if that item is not present (since we're adding).

>>> c = {}
>>> for key in set(a.keys() + b.keys()):
...     c[key] = a.get(key, 0) + b.get(key, 0)
>>> c
{'Cheese': 70, 'coffee': 160, 'Alcohol': 750, 'pulses': 100, 'rice': 100, 'milk': 180}

And a one-liner version of that, if you prefer:

>>> d = {key: a.get(key, 0) + b.get(key, 0) for key in set(a.keys() + b.keys())}
>>> d == c
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download