Here is my one-liner:
# returns False or the value of the end element
reduce(lambda x, y: x and y in x and x[y], list_of_keys, target_dictionary)
Example:
a = {'b': {'c': {'d': True}}}
reduce(lambda x, y: x and y in x and x[y], ['b', 'c', 'd'], a) # True
reduce(lambda x, y: x and y in x and x[y], ['b', 'cd', 'd'], a) # False
How it works: at every iteration of reduce, it checks that previouis keys were in the target dictionary (x
). If not, it will return False because of and
condition immediately and propagate it down the list. Then, it will check if the requested key is in the dict (x in y
). If it is, it will pass the lower level dictionary to the lower level as x
.
Note: the last element (a['b']['c']['d']) has to evaluate to True. If you expect False at the end, check the last level explicitly: 'd' in reduce(...)