Run through a dictionary to insert a value into an object

I have the following dictionary:

dic={} dic["var1"]=val1 dic["var2"]=val2 

Now I have another object that contains two properties: var1 and var2 . I would like to run a loop in an object method such as (pseudocode):

 for key, value in dic self.key=value 

so that self.var1=val2 and self.var2=val2

How can I implement it in python?

Meir

+4
source share
3 answers
 >>> class Obj(object): ... pass ... >>> obj = Obj() >>> for key, value in {'var1':5, 'var2':6}.iteritems(): ... setattr(obj, key, value) ... >>> obj.var1 5 >>> obj.var2 6 

Here I have to say something like "why not just use a dict?"

+3
source

You can use "setattr":

 class Test: var1 = "Cheese" var2 = "Toast" dic = {} dic["var1"] = "NewCheese" dic["var2"] = "NewToast" oTest = Test() for key in dic.keys(): setattr(oTest, key, dic[key]) print "Var1 = ", oTest.var1 print "Var2 = ", oTest.var2 # # Result # # Var1 = NewCheese # Var2 = NewToast # 

See http://docs.python.org/library/functions.html#setattr .

+2
source

You can update the internal __dict__ attribute, which is a dictionary containing all the members of the object.

 class MyObj: def __init__(self, member_dict): self.__dict__.update(member_dict) dic={} dic["var1"]=val1 dic["var2"]=val2 obj = MyObj(dic) print obj.var1 >>> val1 print obj.var2 >>> val2 
+2
source

All Articles