Skip to content

Instantly share code, notes, and snippets.

@maltoze
Last active December 11, 2019 03:27
Show Gist options
  • Save maltoze/df7c78a4c2b858d906d7373958471fa0 to your computer and use it in GitHub Desktop.
Save maltoze/df7c78a4c2b858d906d7373958471fa0 to your computer and use it in GitHub Desktop.
Convert list to tree like list structure https://stackoverflow.com/questions/49853041/
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