Combine two dictionary...

Paul Hankin paul.hankin at gmail.com
Thu Oct 4 11:47:55 EDT 2007


On Oct 4, 4:35 pm, Gary Coulbourne <b... at bears.org> wrote:
> >>> 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

Generalising to support any number of dicts reduces the amount of code
somewhat:

import UserDict

class Merge(UserDict.DictMixin):
    def __init__(self, *args):
        self._dicts = args
        self._keys = list(set(k for d in self._dicts for k in d))
    def keys(self):
        return self._keys
    def __getitem__(self, key):
        return sum(d.get(key, 0) for d in self._dicts)

--
Paul Hankin




More information about the Python-list mailing list