Skip to content

Instantly share code, notes, and snippets.

@xfenix
Created September 9, 2013 15:30
Show Gist options
  • Save xfenix/6497224 to your computer and use it in GitHub Desktop.
Save xfenix/6497224 to your computer and use it in GitHub Desktop.
tree_already_apended = []
tree_childs_key = 'childs'
data = [
dict(
id=1,
parent=None
),
dict(
id=2,
parent=1
),
dict(
id=3,
parent=2
),
dict(
id=4,
parent=3
),
dict(
id=5,
parent=34243
),
dict(
id=6,
parent=5
),
dict(
id=7,
parent=6
),
dict(
id=8,
parent=7
),
dict(
id=9,
parent=8
),
dict(
id=10,
parent=9
),
dict(
id=12,
parent=10
),
dict(
id=13,
parent=12
)
]
def build_tree_wrap(items, root=None):
if not root:
keys = []
for item in items:
keys.append(item['parent'])
root = min(keys)
tree = build_tree(items, root)
if len(tree_already_apended) != len(items):
for item in items:
if item['id'] not in tree_already_apended:
tree.append(
build_tree_item(item, items)
)
return tree
def build_tree(items, root):
tree = []
for item in items:
if item['id'] in tree_already_apended:
continue
if item['parent'] == root:
tree.append(build_tree_item(item, items))
return tree
def build_tree_item(item, items):
processed = dict(name='Test' + str(item['id']))
processed[tree_childs_key] = build_tree(items, item['id'])
processed['leaf'] = False if processed[tree_childs_key] else True
tree_already_apended.append(item['id'])
return processed
def printer(tree, level=0):
for item in tree:
print ' '*level*2 + item['name']
if 'childs' in item:
printer(item['childs'], level + 1)
tree = build_tree_wrap(data)
printer(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment