Recursive tree list from dictionary

David Pratt fairwinds at eastlink.ca
Sat Jan 14 22:16:09 EST 2006


Hi Bengt! I have been banging my head on this one all day! This is 
brilliant (and recursive through each level which is exactly what I was 
trying to work out)! Only part I needed to modify is

else: return title  to  else: return [title]

I tell you, you've made my day! I was getting a bit discouraged trying a 
number of things but just could not get it to work for myself.  Thought 
I'd check the list once more to find that you had worked it out. Many 
thanks Bengt, for this really super and efficient solution!

Regards,
David

> If you literally want "# Project" comments in the output, it will have
> to be a source code (string) output, e.g., the following generates and
> prints both:
> 
> ----< david_pratt.py >--------------------------------------------------
> 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'}
>     ]
> children = {}
> for d in source_list:
>     children.setdefault(d['parent'], []).append(d['title'])
> 
> def get_progeny(title, d=children):
>     if title in d: return [title] + [get_progeny(child) for child in d[title]]
>     else: return title
> 
> source = ['result_list = [']
> result_list = []
> for child in children['root']:
>     source.append('    # %s'%child)
>     source.append('    %r,'% get_progeny(child))
>     result_list.append(get_progeny(child))
> source.append('    ]')
> result_list_source = '\n'.join(source)
> print result_list_source
> print result_list
> ------------------------------------------------------------------------
> 
> [18:20] C:\pywk\clp>py24 david_pratt.py
> result_list = [
>     # Project
>     ['Project', ['Geometries', ['Geometry', 'Points', 'Layers', 'Water']], 'Verticals'],
>     # Soil
>     ['Soil', 'Soiltypes'],
>     ]
> [['Project', ['Geometries', ['Geometry', 'Points', 'Layers', 'Water']], 'Verticals'], ['Soil', '
> Soiltypes']]
> 
> Regards,
> Bengt Richter



More information about the Python-list mailing list