Combine two dictionary...

George Sakkis george.sakkis at gmail.com
Tue Oct 2 13:54:55 EDT 2007


On Oct 1, 2:01 pm, Abandoned <best... at gmail.com> wrote:

> I want to total score..
> For example
>
> > > dict1={1: 4,  3: 5}... and 2 millions element
> > > dict2={3: 3,  8: 6}... and 3 millions element
>
> result should be dict3={1:4, 3:8, 8:6}

Unless you have some prior knowledge about the dicts (e.g.
len(intersection(d1,d2))), it's hard to beat the following, in pure
Python at least:

def sumdicts(d1,d2):
    if len(d1) < len(d2):
        d1,d2 = d2,d1
    dsum = dict(d1)
    for key,value in d2.iteritems():
        if key not in dsum:
            dsum[key] = value
        else:
            dsum[key] += value
    return dsum

Surprisingly (?), this turns out to be faster than using dict.get(key,
0) instead of the explicit if/else.

George




More information about the Python-list mailing list