Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
By request of @hynek :)
# 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