Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python update object from dictionary

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?

like image 822
chakrit Avatar asked Jan 01 '09 21:01

chakrit


People also ask

Can we use update in dictionary Python?

Python Dictionary update methodYou can also update a dictionary by inserting a new value or a key pair to a present entry or by deleting a present entry. The update() method inserts the specified items into the Python dictionary. The specified items can be a dictionary or iterable elements with key-value pairs.

What does .update do in Python?

The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.

Can you update values in a dictionary?

The dict. update() method is used to update a value associated with a key in the input dictionary. The function does not return any values, rater it updates the same input dictionary with the newly associated values of the keys.


1 Answers

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''. 
like image 189
Jehiah Avatar answered Sep 21 '22 04:09

Jehiah