Created
March 22, 2021 10:55
-
-
Save saswata-dutta/44b5110e8604a3ae500ca51512395fc7 to your computer and use it in GitHub Desktop.
json tree walking
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 count(node, target): | |
""" counts occurrences of target in node's hierarchy""" | |
if node == target: | |
return 1 | |
if isinstance(node, list): | |
return sum(count(el, target) for el in node) | |
if isinstance(node, dict): | |
return sum(count(el, target) for el in node.values()) | |
return 0 | |
def path_to(target, node): | |
"""subscript path to target inside node's hierarchy""" | |
if node == target: | |
return f" -> {target!r}" | |
elif isinstance(node, list): | |
for i, el in enumerate(node): | |
path = path_to(target, el) | |
if path: | |
return f"[{i}]{path}" | |
elif isinstance(node, dict): | |
for key, el in node.items(): | |
path = path_to(target, el) | |
if path: | |
return f"[{key!r}]{path}" | |
return None | |
path_to("a1",["a", "b", ["a", {"x" : "a1"}]]) | |
count(["a", "b", ["a", {"x" : "a"}]], "a") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment