Reputation: 183639
Consider a basic adjacency list; a list of nodes represent by a Node class, with properties id
, parent_id
, and name
. The parent_id of top-level nodes = None.
What would be a Pythonic way of transforming the list into an un-ordered html menu tree, e.g.:
Upvotes: 1
Views: 4488
Reputation: 183639
This is how I ended up implementing it- @thg435's way is elegant, but builds a list of dictionaries to print. This one will print an actual HTML UL menu tree:
nodes = [
{ 'id':1, 'parent_id':None, 'name':'a' },
{ 'id':2, 'parent_id':None, 'name':'b' },
{ 'id':3, 'parent_id':2, 'name':'c' },
{ 'id':4, 'parent_id':2, 'name':'d' },
{ 'id':5, 'parent_id':4, 'name':'e' },
{ 'id':6, 'parent_id':None, 'name':'f' }
]
output = ''
def build_node(node):
global output
output += '<li><a>'+node['name']+'</a>'
build_nodes(node['id']
output += '</li>'
def build_nodes(node_parent_id):
global output
subnodes = [node for node in nodes if node['parent_id'] == node_parent_id]
if len(subnodes) > 0 :
output += '<ul>'
[build_node(subnode) for subnode in subnodes]
output += '</ul>'
build_nodes(None) # Pass in None as a parent id to start with top level nodes
print output
You can see it here: http://ideone.com/34RT4
Mine uses recursion (cool) and a global output string (not cool)
Someone could surely improve on this, but it's working for me right now..
Upvotes: 2
Reputation: 214979
Assuming you've got something like this:
data = [
{ 'id': 1, 'parent_id': 2, 'name': "Node1" },
{ 'id': 2, 'parent_id': 5, 'name': "Node2" },
{ 'id': 3, 'parent_id': 0, 'name': "Node3" },
{ 'id': 4, 'parent_id': 5, 'name': "Node4" },
{ 'id': 5, 'parent_id': 0, 'name': "Node5" },
{ 'id': 6, 'parent_id': 3, 'name': "Node6" },
{ 'id': 7, 'parent_id': 3, 'name': "Node7" },
{ 'id': 8, 'parent_id': 0, 'name': "Node8" },
{ 'id': 9, 'parent_id': 1, 'name': "Node9" }
]
This function iterates through the list and creates the tree, collecting children of each node is the sub
list:
def list_to_tree(data):
out = {
0: { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
}
for p in data:
out.setdefault(p['parent_id'], { 'sub': [] })
out.setdefault(p['id'], { 'sub': [] })
out[p['id']].update(p)
out[p['parent_id']]['sub'].append(out[p['id']])
return out[0]
Example:
tree = list_to_tree(data)
import pprint
pprint.pprint(tree)
If parent ids are None's (not 0's), modify the function like this:
def list_to_tree(data):
out = {
'root': { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
}
for p in data:
pid = p['parent_id'] or 'root'
out.setdefault(pid, { 'sub': [] })
out.setdefault(p['id'], { 'sub': [] })
out[p['id']].update(p)
out[pid]['sub'].append(out[p['id']])
return out['root']
# or return out['root']['sub'] to return the list of root nodes
Upvotes: 5