I would like to get a deeply-nested value, for example {"a":{"b":{"c":"myValue"}}
by providing the keys to traverse. I tried chaining together .get() but that didn't work for cases where some of the keys were missing—in those cases, I want to get None
instead.
Could this solution be improved?
#!/usr/bin/env python
# encoding: utf-8
def nestedGet(d,p):
if len(p) > 1:
try:
return nestedGet(d.get(p[0]),p[1:])
except AttributeError:
return None
if len(p) == 1:
try:
return d.get(p[0])
except AttributeError:
return None
print nestedGet({"a":{"b":{"c":1}}},["a","b","c"]) #1
print nestedGet({"a":{"bar":{"c":1}}},["a","b","c"]) #None