Skip to content

Instantly share code, notes, and snippets.

@antonga23
Created April 7, 2021 16:03
Show Gist options
  • Save antonga23/ec0dcb315321843c09a420bab5dcfe1a to your computer and use it in GitHub Desktop.
Save antonga23/ec0dcb315321843c09a420bab5dcfe1a to your computer and use it in GitHub Desktop.
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
#EXAMPLE
# mydict = {
# 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
# 'Grapes':{'Arabian':'25','Indian':'20'} }
# 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment