Strobe_ Strobe_ - 12 days ago 7
Python Question

Check if nested dictionary keys exist

So basically I'm traversing through the nested dictionary

extension
like so:

extension['value1']['value2']['value3']['value4']


However, sometimes the dict file can be a little different:

extension['value1']['value2']['blah1']['value4']


How can I account for this scenario? I don't have to worry about a large number of scenarios, the key will only ever be
value3
or
blah1

Answer

You could write a function to get the first key that exists:

def get_first_item(items, keys):
    for k in keys:
        if k in items:
            return items[k]

    raise KeyError

And then use it like this:

get_first_item(extension['value1']['value2'], ['value3', 'blah1'])['value4']
Comments