Created
April 6, 2021 02:27
-
-
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
This file contains 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 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