Reputation: 515
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
Upvotes: 1
Views: 3729
Reputation: 224962
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']
Upvotes: 2
Reputation: 328
I think the above two answers can well fix your problem. Since your key will be either value3
or blah1
, instead of a function, you may as well use the following code when you loop through the dictionary:
try:
value = extension['value1']['value2']['value3']['value4']
except Exception as e: # except KeyError:
# print(e)
value = extension['value1']['value2']['blah1']['value4']
Upvotes: 2
Reputation: 48092
You have to explicitly check for the key
and then fetch its value. For example:
optional_keys = ['value3', 'blah1']
value = None
for optional_key in optional_keys:
if optional_key in extension['value1']['value2']:
value = extension['value1']['value2'][optional_key]['value4']
break
Upvotes: 2