Skip to content
Advertisement

Elegant way to check if a nested key exists in a dict?

Is there are more readable way to check if a key buried in a dict exists without checking each level independently?

Lets say I need to get this value in a object buried (example taken from Wikidata):

JavaScript

To make sure that this does not end with a runtime error it is necessary to either check every level like so:

JavaScript

The other way I can think of to solve this is wrap this into a try catch construct which I feel is also rather awkward for such a simple task.

I am looking for something like:

JavaScript

which returns True if all levels exists.

Advertisement

Answer

To be brief, with Python you must trust it is easier to ask for forgiveness than permission

JavaScript

The answer

Here is how I deal with nested dict keys:

JavaScript

Example:

JavaScript

Output:

JavaScript

It loop in given element testing each key in given order.

I prefere this to all variable.get('key', {}) methods I found because it follows EAFP.

Function except to be called like: keys_exists(dict_element_to_test, 'key_level_0', 'key_level_1', 'key_level_n', ..). At least two arguments are required, the element and one key, but you can add how many keys you want.

If you need to use kind of map, you can do something like:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement