Skip to content

Instantly share code, notes, and snippets.

@mahmoud
Created December 22, 2018 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmoud/f944deb86cf6deb8caddd074bcaf9b96 to your computer and use it in GitHub Desktop.
Save mahmoud/f944deb86cf6deb8caddd074bcaf9b96 to your computer and use it in GitHub Desktop.
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