我经常需要做这样的事情:
"Some dictionary with values obtained somehow (e.g. submitted form values)"
my_dict = {
'name': 'John',
'surname': 'Doe',
'age': 27,
'hair_color': 'green',
}
"object person is some instance of class representing person"
person.name = my_dict['name']
person.surname = my_dict['surname']
person.age = my_dict['age']
person.hair_color = my_dict['hair_color']
我认为这是很多重复。你用什么方法?
答案 0 :(得分:8)
for attr, val in my_dict.items():
setattr(person, attr, val)
如果my_dict
可能包含您不想复制到person
的任何键,请创建一个您想要复制的键列表并执行以下操作:
key_list = ['name', 'surname', 'age', 'hair_color']
for attr in key_list:
setattr(person, attr, my_dict[attr])
答案 1 :(得分:1)
由于实例的属性可以通过字典访问,因此请使用instance.__dict__
:
>>> for item in my_dict:
person.__dict__[item]=my_dict[item]
答案 2 :(得分:0)
对此已经有了相当不错的问答:How to create objects on the fly in python?
在你的情况下:
person = type('Person', (object,), my_dict)
print person.name