循环遍历字典以向对象插入值

时间:2011-06-01 06:55:17

标签: python

考虑我有以下字典:

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

现在我有另一个包含两个属性的对象:var1var2。 我想在对象的方法中运行一个循环,如(伪代码):

for key, value in dic
  self.key=value

以便self.var1=val2self.var2=val2

如何在python中实现它?

梅尔

3 个答案:

答案 0 :(得分:3)

>>> 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

在这里,我有义务说“为什么不使用字典?”

答案 1 :(得分:2)

您可以使用“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
#

请参阅http://docs.python.org/library/functions.html#setattr

答案 2 :(得分:2)

您可以更新内部__dict__属性,该属性是包含对象所有成员的字典。

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