Created
December 22, 2018 20:27
-
-
Save mahmoud/f944deb86cf6deb8caddd074bcaf9b96 to your computer and use it in GitHub Desktop.
By request of @hynek :)
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
# https://twitter.com/hynek/status/1076048147074478080 | |
from boltons.iterutils import remap | |
DATA = {"a": {"b": 1, "c": {"d": 2}}} | |
OUT = ["a.b", "a.c.d"] | |
def get_leaf_paths(root, with_val=False): | |
""" | |
Returns a list of paths, or path-value tuples if with_val=True, of leaf values in a JSON-serializable structure. | |
""" | |
ret = [] | |
def visit(path, key, value): | |
if not isinstance(value, (dict, list)): | |
full_path = '.'.join([str(p) for p in (path + (key,))]) | |
if with_val: | |
ret.append((full_path, value)) | |
else: | |
ret.append(full_path) | |
return True | |
remap(root, visit=visit, reraise_visit=False) | |
if with_val: | |
return sorted(ret, key=lambda x: x[0]) | |
return sorted(ret) | |
leaf_paths = get_leaf_paths(DATA) | |
assert leaf_paths == OUT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment