Add two dicts

mackstann mack at incise.org
Fri Aug 29 06:22:18 CEST 2003


On Fri, Aug 29, 2003 at 04:11:09AM +0000, Afanasiy wrote:
[ ... ]
> 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?

You can use dict.update(), however, this works in place, so you'll have
to do it outside of the actual string% statement.

d = {"a": 1, "b": 2}
d.update({'x':'123','y':'345'})

print "%(..)s %(..)d ..." % d

-- 
m a c k s t a n n  mack @ incise.org  http://incise.org
So, what's with this guy Gideon, anyway?
And why can't he ever remember his Bible?





More information about the Python-list mailing list