I have a dictionary in python with a pretty standard structure. I want to retrieve one value if present, and if not retrieve another value. If for some reason both values are missing I need to throw an error.
Example of dicts:
# Data that has been modified
data_a = {
"date_created": "2020-01-23T16:12:35+02:00",
"date_modified": "2020-01-27T07:15:00+02:00"
}
# Data that has NOT been modified
data_b = {
"date_created": "2020-01-23T16:12:35+02:00",
}
What is the best practice for this? What could be an intuitive and easily readable way to do this?
The way I do this at the moment:
mod_date_a = data_a.get('date_modified', data_a.get('date_created', False))
# mod_data_a = "2020-01-27T07:15:00+02:00"
mod_date_b = data_b.get('date_modified', data_b.get('date_created', False))
# mod_data_b = "2020-01-23T16:12:35+02:00"
if not mod_date_a or not mod_date_b:
log.error('Some ERROR')
This nested get()
just seems a little clumsy so I was wondering if anyone had a better solution for this.
If you need this often, it would be entirely reasonable to write a function for it:
def get_or_error(d, *keys):
for k in keys:
try:
return d[k]
except KeyError:
pass
else:
raise KeyError(', '.join(keys))
print(get_or_error(data_a, 'date_modified', 'date_created'))
value = data_a['date_modified' if 'date_modified' in data_a else 'date_created']
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