Last active
November 4, 2020 15:52
-
-
Save 0xInfection/18eebcea82eebd1a1c85c19f79fc116b to your computer and use it in GitHub Desktop.
Untangles/flattens a nested dictionary.
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
jd = { | |
"left": { | |
"left": { | |
"type": "Literal", | |
"value": "a" | |
}, | |
"right": { | |
"type": "Literal", | |
"value": "b" | |
} | |
}, | |
"right": { | |
"type": "Literal", | |
"value": "path" | |
} | |
} | |
def builddictdata(pkey, pval): | |
try: | |
for item, itemval in pval.items(): | |
temp1 = pkey + '.' + item | |
yield temp1, itemval | |
except AttributeError: | |
yield pkey, pval | |
# Continue indefinitely until the last depth | |
while True: | |
# starmap is basically map() for iterables | |
mapped = starmap(builddictdata, jd.items()) | |
print(mapped) | |
# chain from iterable will untangle the nested data | |
jd = dict(chain.from_iterable(mapped)) | |
print(jd) | |
# We break out if no more depths are found | |
if not any(isinstance(value, dict) for value in jd.values()): | |
break | |
print(jd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment