Merging dictionaries summing common key values

Merging from Python 3.5

With the following code you can merge two dictionary and get also the sum of the value of the common keys.

a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 3, 'c': 4, 'd': 5}
# this sums the the values of common keys
for k in b:
    if k in a:
        b[k] = b[k] + a[k]
# Merge the two dict with sums of common keys
c = {**a, **b}
print(c)

>>> c
{'a': 1, 'b': 5, 'c': 7, 'd': 5}

Reusable code

In this code, instead, you can do the same thing, but with a function that is callable and so the code is nicer, more readeable and you can use it more times withou having to rewrite the ‘engine’ of the process.

a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 3, 'c': 4, 'd': 5}


def mergsum(a, b):
    for k in b:
        if k in a:
            b[k] = b[k] + a[k]
    c = {**a, **b}
    return c


print(mergsum(a, b))

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.