3

I very often need to do something like this:

"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']

I think this is a lot of repetition. What approach do you use?

Samuel Hapak
  • 6,950
  • 3
  • 35
  • 58

3 Answers3

8
for attr, val in my_dict.items():
    setattr(person, attr, val)

If my_dict might contain any keys that you don't want to copy to person, create a list of keys you do want to copy and do something like this:

key_list = ['name', 'surname', 'age', 'hair_color']
for attr in key_list:
    setattr(person, attr, my_dict[attr])
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • note: make sure you filter/santizie my_dict (restrict the keys), otherwise the user can update arbitrary attributes. – Karoly Horvath Sep 24 '12 at 16:25
  • to restrict the keys you could use an explicit whitelist such as `key_list` even if `my_dict` has no unused keys. – jfs Sep 24 '12 at 16:33
1

As an instance's attributes can be accessed via a dictionary, so use instance.__dict__:

>>> for item in my_dict:
        person.__dict__[item]=my_dict[item]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

There is a pretty good Q/A for this already: How to create objects on the fly in python?

In your case:

person = type('Person', (object,), my_dict)
print person.name
Community
  • 1
  • 1
Benedict
  • 2,771
  • 20
  • 21