Best way to check Python multi-level dictionary

Viewed 6691

Currently I am using the following method, assume dictionary

data[a][b][c]

I use:

if "a" in data and "b" in data["a"] and "c" in data["a"]["b"]:
  ...

Are there any better way?

4 Answers

If you need to do this multi-level lookup very often, this helper method can be useful:

def multi_get(dict_obj, *attrs, default=None):
    result = dict_obj
    for attr in attrs:
        if attr not in result:
            return default
        result = result[attr]
    return result

To use it, just call it like:

x = multi_get(data, 'a', 'b', 'c', default=False)
Related