Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for conditionally getting values from Python dictionary [closed]

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.

like image 305
Kasper Keinänen Avatar asked Jan 27 '20 06:01

Kasper Keinänen


2 Answers

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'))
like image 191
deceze Avatar answered Oct 10 '22 04:10

deceze


value = data_a['date_modified' if 'date_modified' in data_a else 'date_created']
like image 20
Boris Avatar answered Oct 10 '22 05:10

Boris