I have two dictionaries with numerical values. How can I add these two dictionaries such that the resulting dictionary has the same keys but its values is the summation of the values in my original dictionaries?

In other words we are looking for a way to take ` x = {'a':1, 'b': 2} `

and ` y = {'b':10, 'c': 11, 'a':3, 'd':7} `

and output ` {'a': 4, 'c': 11, 'b': 12, 'd': 7} `

.

The following snippet does exactly that by using a couple of little Python tricks like list dictionary comprehensions.

1 2 3 4 5 6 7 8 9 10 |
# # x = {'a':1, 'b': 2} y = {'b':10, 'c': 11, 'a':3, 'd':7} z = {a: x.get(a,0)+y.get(a,0) for a in set(x) | set(y)} print z >>>{'a': 4, 'c': 11, 'b': 12, 'd': 7} |

Let’s analyze this line ` {a: x.get(a,0)+y.get(a,0) for a in set(x) | set(y)}`

`set(x) | set(y)`

produces a set whose keys are the union of the keys for x and y- Hence
`for a in set(x) | set(y)`

results in just the keys for the output set`{'a', 'b', 'c', 'd'}`

`x.get(a,0)`

works just like`x[a]`

with one difference. If a is not among the keys of x it will return 0 instead of throwing a key error- Finally
`a: x.get(a,0)+y.get(a,0)`

generates a dictionary with key a and the value`a: x.get(a,0)+y.get(a,0)`