You can write a recursive function to check:
def f(d, keys): if not keys: return True return keys[0] in d and f(d[keys[0]], keys[1:])
If the function returns True, the keys exist:
In [10]: f(test,"abcd") Out[10]: True In [11]: f(test,"abce") Out[11]: False
If you want to test several key combinations:
for keys in ("abce","abcr","abcd"): if f(test,keys): print(keys) break abcd
To return a value, this is pretty simple:
def f(d, keys): if len(keys) == 1: return d[keys[0]] if keys[0] in d else False return keys[0] in d and f(d[keys[0]], keys[1:]) print(f(test,"abcd")) e
Try again for a few key combinations:
def test_keys(keys): for keys in keys: val = f(test,keys) if val: return val return False print(test_keys(("abce","abcr","abc")))
You can also write the function iteratively:
def f(d, keys): obj = object for k in keys: d = d.get(k, obj) if d is obj: return False return d print(f(test,"abcd")) e
If you want to run a condition based on the return values:
def f(d, keys): obj = object for k in keys: d = d.get(k, obj) if d is obj: return False return d from operator import mul my_actions = {"c": mul(2, 2), "d": lambda: mul(3, 3), "e": lambda: mul(3, 3)} for st in ("abce", "abcd", "abcf"): val = f(test, st) if val: print(my_actions[val]()) 9
Just check the key combination in the same order as with if / elif, etc.