1👍
✅
First in your mapping don’t use the name of the conversion function but the function itself, ie:
def convert_DOB(dob):
# your code here
# ...
field_mappings = {
# ...
'DOB': ['Geboortedatum', convert_DOB],
# ...
}
Then you just have to pass your value to the function and retrieve the result:
for attrname, sourcekey in field_mappings.items():
if isinstance(sourcekey, list):
# unpack the list (assumes length 2)
sourcekey, converter = key
value = result[sourcekey]['0']
# convert the value
value = converter(value)
else:
# no conversion needed
value = result[sourcekey]['0']
# done
setattr(patient, attrname, value)
Note that from a purely semantic POV you should be using a tuple not a list – a list is supposed to be an h*m*genous collection where position is not significant, a tuple is an heterogenous collection where poistion is significant. In your case the position is indeed significant since the first item is the key to the results dict and the second the conversion function.
Also the way you use field_mappings
suggests you could replace it with a list of (attrname, key_or_key_converter) tuples since you only iterate over the dict’s (key, value) pairs.
Source:stackexchange.com