2Cubed 2Cubed - 4 months ago 13
Python Question

Search nested dicts for key trees

I would like to check if a tuple of keys exists in a nested dictionary, similarly to

dict.get
. The functionality can be achieved as follows.

nested_dict = {
'x': 1,
'a': {
'b': {
'c': 2,
'y': 3
},
'z': 4
}
}

def check(nested, *path):
for key in path:
if isinstance(nested, dict) and key in nested:
nested = nested[key]
else:
return False
return True


check(nested_dict, 'a', 'b', 'c') # True
check(nested_dict, 'x') # True
check(nested_dict, 'a', 'b', 'y') # True
check(nested_dict, 'a', 'z') # True

check(nested_dict, 'y') # False
check(nested_dict, 'a', 'y') # False
check(nested_dict, 'a', 'b', 'c', 'y') # False


Is there a cleaner (or better yet, built-in) method of doing this?

Answer

For python 3.x do from functools import reduce.

You can wrap a try .. except KeyError (and TypeError) and return the appropriate boolean value:

>>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict)
2
>>> reduce(lambda x,y: x[y], ["a", "b", "d"], nested_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
KeyError: 'd'

PS: These one lines are sometimes fun to write. But I'd honestly use your version for any production code.