Recursive tree list from dictionary

David Pratt fairwinds at
Sat Jan 14 15:46:29 EST 2006

Hi Allan, Max, and bearophile

Many thanks for your replies to this. The number of levels can be deeper 
than two for creating child, sibling relationships. This can lead to 
futher nesting as shown in my sample result list (the result I am 
attempting to acheive) which is reason that I believe this has to be 
recursive to work. As an illustration, I have altered the source_dict to 
show this by making Geometries the parent of Geometry. I should have 
gone one more level to illustrate this properly - my apologies for not 
doing this better.

source_list = [{'title': 'Project', 'parent':'root'},
	{'title': 'Geometry', 'parent':'Geometries'},
	{'title': 'Soil', 'parent':'root'},
	{'title': 'Geometries', 'parent':'Project'},
	{'title': 'Verticals', 'parent':'Project'},
	{'title': 'Points', 'parent':'Geometry'},
	{'title': 'Layers', 'parent':'Geometry'},
	{'title': 'Water', 'parent':'Geometry'},
	{'title': 'Soiltypes', 'parent':'Soil'}

Project and Soil in root,
Geometries (Geometries containing Geometry with its siblings) and 
Verticals in Project,
Soiltypes in Soil

In this instance, I am looking for a result list that looks like this:

result_list = [
	# Project
	['Project', ['Geometries',['Geometry', ['Points', 
	# Soil
	['Soil', ['Soiltypes']]

I have not yet installed but 
will also give this a try. What I need is something like elementree 
minus the xml since I am working with list of dicts obtained from more 
than one type of source.


>>>>for d in source_list:
> 	par=d['parent']
> 	v=d['title']
> 	try:
> 		imd[par].append(v)
> 	except:
> 		imd[par]=[v]
> {'Project': ['Geometries', 'Verticals'], 'Geometry': ['Points',
> 'Layers', 'Water'], 'root': ['Project', 'Geometry', 'Soil'], 'Soil':
> ['Soiltypes']} 
> max

More information about the Python-list mailing list