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.