Add two dicts

Alex Martelli aleax at aleax.it
Sat Aug 30 09:52:51 CEST 2003


Greg Brunet wrote:

> "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)
   ...
> Ooops - that should have been:
>         return result.update(dict2)
> 
> in the last line, but still, shouldn't that have mapped the "+" operator
> for xdict objects?

You're returning None in both your actual code and the "should have been", 
but the general approach is workable -- e.g. with Python 2.3:

>>> class xdict(dict):
...     def __add__(self, other):
...         return xdict(self, **other)
...
>>> xdict({1:2, 3:4})+{5:6}
{1: 2, 3: 4, 5: 6}
>>>

Alex





More information about the Python-list mailing list