Skip to content

Instantly share code, notes, and snippets.

@bulatie
Created August 7, 2017 13:13
Show Gist options
  • Save bulatie/f25f9539ad1d49e15161ff41deaad233 to your computer and use it in GitHub Desktop.
Save bulatie/f25f9539ad1d49e15161ff41deaad233 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
list = [{
'name': 'a',
'id': 1,
'pid': 0
}, {
'name': 'b',
'id': 2,
'pid': 1
}, {
'name': 'c',
'id': 3,
'pid': 1
}, {
'name': 'd',
'id': 4,
'pid': 2
}, {
'name': 'e',
'id': 5,
'pid': 2
}, {
'name': 'f',
'id': 6,
'pid': 3
}]
pDict = {}
for item in list:
if item['pid'] in pDict:
pDict[item['pid']].append(item)
else:
pDict[item['pid']] = []
pDict[item['pid']].append(item)
print(pDict)
def buildTree(pid):
unitTree = {}
if pid not in pDict:
return {}
for item in pDict[pid]:
item['nodes'] = buildTree(item['id'])
unitTree[item['id']] = item
return unitTree
tree = buildTree(0)
print(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment