Python update object from dictionary

Question:

Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?

This is what I intend to do:

c = MyClass()
c.foo = 123
c.bar = 123

# c.foo == 123 and c.bar == 123


d = {'bar': 456}
c.update(d)

# c.foo == 123 and c.bar == 456

Something akin to dictionary update() which load values from another dictionary but for plain object/class instance?

Asked By: chakrit

||

Answers:

Have you tried

f.__dict__.update( b )

?

Answered By: S.Lott

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.

Answered By: hyperboreean

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''.
Answered By: Jehiah

You can try doing:

def to_object(my_object, my_dict):
    for key, value in my_dict.items():
        attr = getattr(my_object, key)
        if hasattr(attr, '__dict__'):
            to_object(attr, value)
        else:
            setattr(my_object, key, value)

obj = MyObject()
data = {'a': 1, 'b': 2}
to_object(obj, data)
Answered By: Trong Pham
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.