Skip to content

Instantly share code, notes, and snippets.

@jclosure
Created April 6, 2021 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclosure/9d458c8da17bf9e20a2d9cff10b988b2 to your computer and use it in GitHub Desktop.
Save jclosure/9d458c8da17bf9e20a2d9cff10b988b2 to your computer and use it in GitHub Desktop.
Generator for flattening nested dicts into a lists of path parts and value at the end
def dict_generator(indict, pre=None):
pre = pre[:] if pre else []
if isinstance(indict, dict):
for key, value in indict.items():
if isinstance(value, dict):
for d in dict_generator(value, pre + [key]):
yield d
elif isinstance(value, list) or isinstance(value, tuple):
for v in value:
for d in dict_generator(v, pre + [key]):
yield d
else:
yield pre + [key, value]
else:
yield pre + [indict]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment