Skip to content

Instantly share code, notes, and snippets.

@Dleau
Created December 18, 2019 03:53
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 Dleau/7ddba7e97cd60ea3329c18a089ded679 to your computer and use it in GitHub Desktop.
Save Dleau/7ddba7e97cd60ea3329c18a089ded679 to your computer and use it in GitHub Desktop.
csvify, JSON to CSV translation
# recursively traverse a dictionary, concatenate key names,
# then map those names to values
# extremely useful in JSON to CSV translation
def helper(d, path=[]):
if isinstance(d, dict):
for root, child in d.items():
yield from helper(child, path + [root])
else: yield path + [d]
def csvify(d):
for l in helper(d):
key = '.'.join(x for x in l[:-1])
val = l[-1]
print("%s --> %s" % (key, val))
d = {'a': {'a': 1, 'b': 2, 'c': 3}, 'b': {'e': {'x': 4}, 'f': 1}, 'c': 3}
csvify(d)
# a.a --> 1
# a.b --> 2
# a.c --> 3
# b.e.x --> 4
# b.f --> 1
# c --> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment