Created
April 7, 2021 16:03
-
-
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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