Add two dicts

Greg Brunet gregbrunet at NOSPAMsempersoft.com
Sat Aug 30 09:48:20 CEST 2003


"Greg Brunet" <gregbrunet at NOSPAMsempersoft.com> wrote in message
news:vl0heutm63na0 at corp.supernews.com...
> "Greg Brunet" <gregbrunet at NOSPAMsempersoft.com> wrote in message
> news:vl0gbotgl3sibf at corp.supernews.com...
> > But what about something like this:
> >
> > >>> class xdict(dict):
> > ...  def __add__(self,dict2):
> > ...   result = self.copy()
> > ...   result = result.update(dict2)

... I was getting sloppy in the interactive mode.  Instead I did this &
it seems to work properly:


class xdict(dict):
    def add(self,dict2):
        result = self.copy()
        result.update(dict2)
        return result

    def __add__(self,dict2):
        result = self.copy()
        result.update(dict2)
        return result

    def __iadd__(self,dict2):
        self.update(dict2)
        return self

a=xdict({'x':1})
b=xdict({'y':2})
print
print "Add:", a.add(b)
print "+:", a+b
print "a:",a,"b:",b
a+=b
print "+= (a=):", a

Results:
Add: {'y': 2, 'x': 1}
+: {'y': 2, 'x': 1}
a: {'x': 1} b: {'y': 2}
+= (a=): {'y': 2, 'x': 1}


-- 
Greg





More information about the Python-list mailing list