You can build a simple approach, using the built-in library, as below:
from functools import reduce, partial
from operator import getitem
nested_get = partial(reduce, getitem)
x = {'a': {'b': {'c': {'d': 1}}}}
item = nested_get(["a", "b", "c", "d"], x)
print(item)
Output
1
UPDATE
To emulate the behavior of dict.get
, use:
def nested_get(path, d, default=None):
current = d
for key in path:
try:
current = current[key]
except KeyError:
return default
return current
x = {'a': {'b': {'c': {'d': 1}}}}
item = nested_get(["a", "b", "c", "d"], x)
print(item)
item = nested_get(["a", "b", "e", "d"], x)
print(item)
Output
1
None