Add two dicts

Alex Martelli aleax at aleax.it
Fri Aug 29 04:48:30 EDT 2003


Afanasiy wrote:

> I have some code like this...
> 
>   self.write(
>     '''
>     lots of stuff here with %(these)s named expressions
>     '''
>     % vars(self)
>   )
> 
> Then I wanted to add an item to the dict vars(self), so I tried :
> 
>   vars(self)+{'x':'123','y':'345'}
> 
> This doesn't work, perhaps because no one could decide what should happen
> to keys which already exist in the dict? (I'd say throw an exception).
> 
> 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?

In Python 2.3, you can, if you wish, code:

   self.write(
     '''
     lots of stuff here with %(these)s named expressions
     '''
     % dict(vars(self), x='123', y='345')
   )

thanks to the new feature of dict of allowing a **kwds argument (with
the 'obvious' semantics, however: named keys override keys already
present in the first argument -- if you need to diagnose overlap and
raise an exception thereupon, you'll have to do that separately).

More generally, if you had an existing dict D you wanted to "add" to
vars(self), rather than a literal, you could code:

   self.write(
     '''
     lots of stuff here with %(these)s named expressions
     '''
     % dict(vars(self), **D)
   )


Alex





More information about the Python-list mailing list