Combine two dictionary...

Gary Coulbourne bear at bears.org
Thu Oct 4 17:35:03 CEST 2007


>>> dict1={1: 4,  3: 5}... and 2 millions element
>>> dict2={3: 3,  8: 6}... and 3 millions element

If you don't mind doing some kind of lazy evaluation, you could do
something like...

------------------------------
dict1={1:4, 3:5}
dict2={3:3, 8:6}

import UserDict

class Merge(UserDict.DictMixin):

   def __init__(self,d1,d2):
       self.dict1 = d1
       self.dict2 = d2

       keyset = set(d1.keys())
       keyset.update(d2.keys())

       self.dkeys = list(keyset)


   def keys(self):
       return self.dkeys

   def __getitem__(self,key):
       v1 = 0
       v2 = 0
       if key in self.dict1:
          v1 = self.dict1[key]
       if key in self.dict2:
          v2 = self.dict2[key]
       return v1+v2

m = Merge(dict1,dict2)

print m
------------------------------

This basically does a sort of "virtual merge"... only merging when you
actually ask for an element in the list.

-- 
--------------------------------------------------------------------
    Gary Coulbourne                        Software Developer
                                           C/C++, Java, Perl, Python



More information about the Python-list mailing list