Last active
December 11, 2019 03:27
-
-
Save maltoze/df7c78a4c2b858d906d7373958471fa0 to your computer and use it in GitHub Desktop.
Convert list to tree like list structure https://stackoverflow.com/questions/49853041/
This file contains hidden or 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 tree_to_format(tree): | |
ret = [] | |
for k in tree: | |
ret.append({'name': k, 'children': tree_to_format(tree[k])}) | |
return ret | |
def items_to_tree(items): | |
dic = {} | |
for parts in items: | |
cursor = dic | |
last = parts.pop() | |
for part in parts: | |
if part not in cursor: | |
cursor[part] = {} | |
cursor = cursor[part] | |
cursor[last] = {} | |
return dic | |
tree = items_to_tree([['a', 'b'], ['a', 'c', 'd'], ['b', 'c']]) | |
tree_to_format(tree) | |
''' | |
input: | |
[['a', 'b'], ['a', 'c', 'd'], ['b', 'c']] | |
output: | |
[{'name': 'a', 'children': [{'name': 'b', 'children': []}, {'name': 'c', 'children': [{'name': 'd', 'children': []}]}]}, | |
{'name': 'b', 'children': [{'name': 'c', 'children': []}]}] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment