Add two dicts

John Roth newsgroups at jhrothjr.com
Sat Aug 30 13:36:41 CEST 2003


"Greg Brunet" <gregbrunet at NOSPAMsempersoft.com> wrote in message
news:vl0gbotgl3sibf at corp.supernews.com...
> "Alex Martelli" <aleax at aleax.it> wrote in message
> news:BjE3b.7850$aG6.251286 at news1.tin.it...
> > Afanasiy wrote:
> >
> > > On Thu, 28 Aug 2003 22:07:06 -0700, Erik Max Francis
> <max at alcyone.com>
> > > wrote:
> > >
> > >>Afanasiy wrote:
> > >>
> > >>> Can I add two dicts in a way which is not cumbersome to the above
> %
> > >>> string
> > >>> operation? Is this another case of writing my own function, or
> does a
> > >>> builtin (or similar) already exist for this?
> > >>
> > >>combinedDict = aDict.copy()
> > >>combinedDict.update(anotherDict)
> > >>
> > >>If that's cumbersome, don't really know what you'd consider
> > >>non-cumbersome.
> > >
> > > Don't really know if you're asking, but :
> > >
> > >   vars(self)+{'x':'123','y':'345'}
> > >
> > > I would consider that non-cumbersome. ;-)
> >
> > So, what about:
> >
> > def dict_add(adict, another):
> >     result = adict.copy()
> >     result.update(another)
> >     return result
> >
> > and then dict_add(vars(self),  {'x':'123','y':'345'}) ?  But in fact
> > you can do even better...:
> >
> ... lots of other good ideas...
>
> But what about something like this:
>
> >>> class xdict(dict):
> ...  def __add__(self,dict2):
> ...   result = self.copy()
> ...   result = result.update(dict2)
> ...
>
> I was hoping that would allow:
> >>> a=xdict({'y': 456, 'x': 111})
> >>> b=xdict({'y': 444, 'z': 789})
> >>> a+b
>
> but instead of the result which I hoped for, I get the following:
>
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: unsupported operand type(s) for +: 'xdict' and 'xdict'
>
> So I can't implement '+' operator for dictionaries - why not?

The special functions can only be defined in the class
definition. They cannot be added afterwards. This is a
compiler optimization to avoid having to do dictionary
lookups on every operator.

If you want to do this, subclass dict.

John Roth
>
> -- 
> Greg
>
>
>






More information about the Python-list mailing list