Consider a dict like
mydict = {
\'Apple\': {\'American\':\'16\', \'Mexican\':10, \'Chinese\':5},
\'Grapes\':{\'Arabian\':\'25\',\'Indian\':\'20\'} }
With the following small function, digging into a tree-shaped dictionary becomes quite easy:
def dig(tree, path):
for key in path.split("."):
if isinstance(tree, dict) and tree.get(key):
tree = tree[key]
else:
return None
return tree
Now, dig(mydict, "Apple.Mexican")
returns 10
, while dig(mydict, "Grape")
yields the subtree {'Arabian':'25','Indian':'20'}
. If a key is not contained in the dictionary, dig
returns None
.
Note that you can easily change (or even parameterize) the separator char from '.' to '/', '|' etc.