Last active
September 7, 2020 20:43
-
-
Save akey7/0038cc55c6b07230d5748a59f258e86f to your computer and use it in GitHub Desktop.
Recursive Structure Traversal
This file contains 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
from typing import Any | |
def rst(root: Any, key: str = "root") -> None: | |
if type(root) is dict and len(root.keys()) > 0: | |
for k, v in root.items(): | |
rst(v, f"{key}['{k}']") | |
elif type(root) is dict and len(root.keys()) == 0: | |
print(">>> Skipping key with empty dictionary as value", key) | |
elif type(root) is list and len(root) > 0 and type(root[0]) is dict: | |
for i, x in enumerate(root): | |
rst(x, f"{key}[{i}]") | |
else: | |
print(key, root) | |
if __name__ == "__main__": | |
simple = { | |
"alpha": { | |
"zulu": "yankee", | |
"victor": "uniform", | |
} | |
} | |
moderate = { | |
"alpha": { | |
"zulu": "yankee", | |
"victor": "uniform", | |
"bravo": [ | |
1, | |
"awesome", | |
"list", | |
], | |
} | |
} | |
hard = { | |
"alpha": { | |
"zulu": "yankee", | |
"victor": "uniform", | |
"bravo": [ | |
1, | |
"awesome", | |
"list", | |
], | |
"delta": [ | |
{ | |
"deeper": "recursion", | |
"what would be": "the iterative solution?", | |
} | |
], | |
"echo": [], | |
"golf": {}, | |
} | |
} | |
rst(hard) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment