Say I want to write a function which will return an arbitrary value from a dict, like: mydict['foo']['bar']['baz']
, or return an empty string if it doesn't. However, I don't know if mydict['foo']
will necessarily exist, let alone mydict['foo']['bar']['baz']
.
I'd like to do something like:
safe_nested(dict, element):
try:
return dict[element]
except KeyError:
return ''
But I don't know how to approach writing code that will accept the lookup path in the function. I started going down the route of accepting a period-separated string (like foo.bar.baz
) so this function could recursively try to get the next sub-dict, but this didn't feel very Pythonic. I'm wondering if there's a way to pass in both the dict (mydict
) and the sub-structure I'm interested in (['foo']['bar']['baz']
), and have the function try to access this or return an empty string if it encounters a KeyError
.
Am I going about this in the right way?