Skip to content

Python: adding two dicts together

An answer to this question on Stack Overflow.

Question

Alrigt, lets say I have these two dictionaries:

A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}

I am trying to add them together such that I get a dict similar to this:

C = {(3,'x'):-2,(3,'y'):4, (6,'y'):9, (8, 'b'):9}

I have tried making a comprehension that does this for dicts of any lenght. But it seems a bit difficult for a newbie. I am at a level where I try stuff like this for example:

Edited:

>>> {k:A[k]+B[d] for k in A for d in B}
{(6, 'y'): 7, (3, 'x'): 2, (8, 'b'): 13}

I get this far due to help but it leaves out the (3,'y'):4 for some reason

Answer

This may not be the most efficient method, but it's more general.

#!/usr/bin/python
A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
B = {(3,'y'):4, (6,'y'):6}
dd={}
for d in (A, B): #Put as many dictionaries as you would like here
  for key, value in d.iteritems():
    dd[key] = dd.get(key, 0) + value