Python update object from dictionary

there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in c.__dict__ which isn't always true.

d = {'bar': 456}
for key,value in d.items():
    setattr(c,key,value)

or you could write a update method as part of MyClass so that c.update(d) works like you expected it to.

def update(self,newdata):
    for key,value in newdata.items():
        setattr(self,key,value)

check out the help for setattr

setattr(...)
    setattr(object, name, value)
    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ''x.y = v''.

Have you tried

f.__dict__.update( b )

?


Also, maybe it would be good style to have a wrapper around the dict's update method:

def update(self, b):
    self.__dict__.update(b)

PS: Sorry for not commenting at @S.Lott 's post but I don't have the rep yet.