Combine two dictionary...

Tim Chase python.list at tim.thechases.com
Mon Oct 1 21:00:25 CEST 2007


>> 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}
> 
> Well not sure how this will work with 5+ million elements, but here's 
> one stab at it:
> 
>      >>> dict1={1: 4,  3: 5}
>      >>> dict2={3: 3,  8: 6}
>      >>> for key in set(dict1.keys() + dict2.keys()):
>      ...     x = dict1.get(key, 0)
>      ...     y = dict2.get(key, 0)
>      ...     dict3[key] = x + y
>      ...
>      >>> dict3
>      {8: 6, 1: 4, 3: 8}

Or if doing it in-place is sufficient, you can use

   for k,v in dict2.iteritems():
     dict1[k] = dict1.get(k, 0) + v

Or, if you like stupid iterator/comprehension tricks

   dict1.update(
     (k,dict1.get(k, 0) + v)
     for k,v in dict2.iteritems()
     )

-tkc






More information about the Python-list mailing list