I have a dictionary which is populated from xml. Dictionary has a lot of key-value pairs. I have to populate a custom object with values from that dictionary. I want to catch exception if one key in dictionary is not present or the value is not the expected type, log which key and continue execution. Is there a better way than surrounding each line with try expect block. To be specific I want to avoid this syntax, it does what I need, but I'm wondering if there is a more efficient solution:
try:
my_object.prop1 = dictionary['key1']
except Exception as e:
log.write('key1')
try:
my_object.prop2 = dictionary['key2']
except Exception as e:
log.write('key2')
try:
my_object.prop3 = dictionary['key3']
except Exception as e:
log.write('key3')
....
Do it programmatically.
props_keys = {
'prop1': 'key1'
'prop2': 'key2',
'prop3': 'key3'
}
for prop, key in props_keys.iteritems():
try:
setattr(myobj, prop, mydict[key])
except KeyError:
log(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With