Created
December 18, 2019 03:53
-
-
Save Dleau/7ddba7e97cd60ea3329c18a089ded679 to your computer and use it in GitHub Desktop.
csvify, JSON to CSV translation
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
# 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