tags:

views:

93

answers:

3

Possible Duplicate:
How do you programmatically set an attribute in Python?

Hey, here's a dumb question: how can I set an object property given its name in a string. I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this:

    for entry in src_dict:
          if entry.startswith('can_'):
              tgt_obj[entry] = src_dict_profile[entry]

I'm still a bit of a noob with Python so would appreciate some help. - dave.

+4  A: 

Sounds like you're looking for setattr.

Example:

for entry in src_dict:
      if entry.startswith('can_'):
          setattr(tgt_obj, entry, src_dict_profile[entry])
Hank Gay
+4  A: 
setattr(some_object, 'some_attribute', 42);
Deniz Dogan
A: 

On objects that have "dict" property

if "__dict__" in dir(obj):

you may do fun things like:

obj.__dict__.update(src_dict)
ddotsenko