Post date: Feb 1, 2011 5:59:44 PM
http://blog.adambachman.org/2008/06/simple-tree-using-python-dictionary.html
# simple tree builder.
# (node, parent, title)
els = (
(1, 0, 'a'),
(2, 1, 'b'),
(3, 1, 'c'),
(4, 0, 'd'),
(5, 4, 'e'),
(6, 5, 'f'),
(7, 4, 'g')
)
class Node:
def __init__(self, c_id, c_title):
self.id = c_id
self.title = c_title
self.children = []
treeMap = {}
Root = Node(0, "Root")
treeMap[Root.id] = Root
for element in els:
nodeId, parentId, title = element
if not nodeId in treeMap:
treeMap[nodeId] = Node(nodeId, title)
else:
treeMap[nodeId].id = nodeId
treeMap[nodeId].title = title
if not parentId in treeMap:
treeMap[parentId] = Node(0, '')
treeMap[parentId].children.append(treeMap[nodeId])
def print_map(node, lvl=0):
for n in node.children:
print ' ' * lvl + n.title
if len(n.children) > 0:
print_map(n, lvl+1)
print_map(Root)
"""
Output:
a
b
c
d
e
f
g
"""