Skip to content

Instantly share code, notes, and snippets.

@0xInfection
Last active November 4, 2020 15:52
Show Gist options
  • Save 0xInfection/18eebcea82eebd1a1c85c19f79fc116b to your computer and use it in GitHub Desktop.
Save 0xInfection/18eebcea82eebd1a1c85c19f79fc116b to your computer and use it in GitHub Desktop.
Untangles/flattens a nested dictionary.
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