Add two dicts

Michele Simionato mis6 at pitt.edu
Fri Aug 29 08:40:15 EDT 2003


Afanasiy <abelikov72 at hotmail.com> wrote in message news:<86ktkvkd05e88hu14hjudmfvbul7slfgkt at 4ax.com>...
> 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?

Here is a possibile solution:

class attributes(dict):
    def __init__(self,obj):
        if isinstance(obj,dict):
            self.update(obj)
        elif hasattr(obj,'__dict__'):
            self.update(obj.__dict__)
        else:
            raise TypeError("Dictionary or object with a __dict__ required")
    def __add__(self,other):
        self.update(other)
        return self.__class__(self)
    __radd__=__add__

class C(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y


c=C(1,2)
print attributes(c)
print attributes(c)+{'z':3}
print {'z':3}+attributes(c)


Michele Simionato, Ph. D.
MicheleSimionato at libero.it
http://www.phyast.pitt.edu/~micheles
--- Currently looking for a job ---

http://www.strakt.com/dev_talks.html

http://www.ibm.com/developerworks/library/l-pymeta2/?ca=dnt-434




More information about the Python-list mailing list