Tim Chase python.list at tim.thechases.com
Wed Oct 18 18:37:25 CEST 2006

> However It does not work as I would need.
> Let's suppose I have
>  a={'c':1,'d':2}
>  b={'c':2}
> but
>  a.update(b)
> will make
> {'c': 2, 'd': 2}
> and I would need
> {'c': 3, 'd': 2}

Ah...a previously omitted detail.

There are likely a multitude of ways to do it.  However, the one 
that occurs to me off the top of my head would be something like

dict((k, a.get(k, 0) + b.get(k, 0)) for k in a.keys()+b.keys())

If the sets are huge, you can use itertools

 >>> from itertools import chain
 >>> dict((k, a.get(k, 0) + b.get(k, 0)) for k in 
{'c': 3, 'd': 2}

which would reduce the need for creating the combined dictionary, 
only to throw it away.


More information about the Python-list mailing list