Created
February 1, 2018 08:41
-
-
Save alanduan/55852fd90b2b433ad77ab6adf3981e4c to your computer and use it in GitHub Desktop.
flatten data structure
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 flat(content): | |
path = [] | |
flatten(content, path) | |
def flatten(content, path): | |
if type(content) is list or type(content) is tuple: | |
for index, node in enumerate(content): | |
cur_path = path[:] | |
cur_path.append(str(index)) | |
flatten(node, cur_path) | |
elif type(content) is dict: | |
for key, node in content.items(): | |
cur_path = path[:] | |
cur_path.append(key) | |
flatten(node, cur_path) | |
else: | |
print(('/'.join(path), content)) | |
test = { | |
"key1": 42, | |
"key2": "some string", | |
"key3": [1, 2], | |
"key4": [{"sk1": [4,5], "sk2": "blah"}, ("hello", "world")], | |
"key5": { | |
'sub1': { | |
'sub11': 'v1', | |
'sub12': 'v2', | |
}, | |
'sub2': ['abc', 1234, ('wow', 'hum', (4321, 'xxxx', {'a': 63, 'b': 64}))] | |
} | |
} | |
flat(test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment