pythondictionary

Python program to combine two dictionary adding values for common keys


I have two dictionaries and I need to combine them. I need to sum the values of similar keys and the different keys leave them without sum.

These are the two dictionaries:

d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}

The expected results:

d3= {'b': 400, 'd': 400, 'a': 400, 'c': 300}

I have successfully made the sum and added them to this third dictionary, but I couldn't know, how to add the different values.

My try

d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d3 = {}

for i, j in d1.items():
    for x, y in d2.items():
        if i == x:
            d3[i]=(j+y)


print(d3)


My results = {'a': 400, 'b': 400}

Solution

  • I like Andrej's answer (I LOVE list/dict comprehensions), but here's yet another thing:

    d1 = {'a': 100, 'b': 200, 'c':300}
    d2 = {'a': 300, 'b': 200, 'd':400}
    
    d3 = dict(d1) # don't do `d3=d1`, you need to make a copy
    d3.update(d2) 
    
    for i, j in d1.items():
        for x, y in d2.items():
            if i == x:
                d3[i]=(j+y)
    
    
    print(d3)
    

    I realised your own code can be "fixed" by first copying values from d1 and d2.

    d3.update(d2) adds d2's contents to d3, but it overwrites values for common keys. (Making d3's contents {'a':300, 'b':200, 'c':300, 'd':400})

    However, by using your loop after that, we correct those common values by assigning them the sum. :)