Bhawan
Bhawan

Reputation: 2491

Merge two dictionaries and if duplicate keys found , add their values

I have 2 python dictionaries:

x =  {'bookA': 1, 'bookB': 2, 'bookC': 3, 'bookD': 4, 'bookE': 5}  
y =  {'bookB': 1, 'bookD': 2, 'bookF': 3, 'bookL': 4, 'bookX': 5}

I want to merge the above two dictionaries and create an another dictionary. I tried this code:

z = {**x, **y}

But the key values are overriding in this case. I want a dictionary in which if there are duplicates , add their values or some other action can also be there like subtraction, multiplication etc. So my motto is not to override the duplicate values but to perform some action if got any duplicate. Any help would be highly appreciated.

Upvotes: 2

Views: 1719

Answers (2)

fantabolous
fantabolous

Reputation: 22716

cs95's solutions are nice, but for the sake of options, here's a 1-liner comprehension:

x.update({k:(v + x[k]) if k in x else v for k,v in y.items()})

That modifies your x dict in-place; if you can't do that then copy it to z first:

z = x.copy()
z.update({k:(v + z[k]) if k in z else v for k,v in y.items()})

Upvotes: 0

cs95
cs95

Reputation: 402433

Option 1
Convert x and y to collections.Counter objects and just sum them (Counter supports __add__ition.)

from collections import Counter

z = dict(Counter(x) + Counter(y))
z 
{'bookA': 1,
 'bookB': 3,
 'bookC': 3,
 'bookD': 6,
 'bookE': 5,
 'bookF': 3,
 'bookL': 4,
 'bookX': 5}

Option 2
You can write a neat little dict comprehension using dict.pop -

z = {k : x[k] + y.pop(k, 0) for k in x} 

Now, update z with what's left in y -

z.update(y)

Or,

z = {**z, **y} # python3.6

z
{'bookA': 1,
 'bookB': 3,
 'bookC': 3,
 'bookD': 6,
 'bookE': 5,
 'bookF': 3,
 'bookL': 4,
 'bookX': 5}

Upvotes: 4

Related Questions