convert flat structure into hierarchical one

Mike C. Fletcher mcfletch at rogers.com
Sun Sep 26 17:23:59 EDT 2004


This is not the most elegant approach, but then I hacked it up without 
any planning in the interpreter...

 >>> data = [(1, 'grandparent', None), (2, 'parent', 1), (3, 
'otherparent', 1), (4, 'child', 3)]
 >>> nodes = dict( [ (a[0],(a[1],a[2],[])) for a in data ] )
 >>> nodes
{1: ('grandparent', None, []), 2: ('parent', 1, []), 3: ('otherparent', 
1, []), 4: ('child', 3, [])}
 >>> roots = []
 >>> for key,value in nodes.items():
...     parent = nodes.get( value[1], ('noname',None,roots))
...     parent[2].append( (key,value) )
...
 >>> roots
[(1, ('grandparent', None, [(2, ('parent', 1, [])), (3, ('otherparent', 
1, [(4, ('child', 3, []))]))]))]
 >>> import pprint
 >>> pprint.pprint( roots )
[(1,
  ('grandparent',
   None,
   [(2, ('parent', 1, [])),
    (3, ('otherparent', 1, [(4, ('child', 3, []))]))]))]
 >>> nodes[3]
('otherparent', 1, [(4, ('child', 3, []))])
 >>> nodes[2]
('parent', 1, [])

If you really wanted, you could convert each "children" list into a 
dictionary, or leave the children's identity in their tuple.

HTH,
Mike

Ksenia Marasanova wrote:

> I get this kind of list from a database. (The tuple structure is: id, 
> name, parent_id)
>
> [(1, 'grandparent', None), (2, 'parent', 1), (3, 'otherparent', 1), 
> (4, 'child', 3)]
>
> I would like to transfer it (in Python) into a tree structure. I don't 
> care much about format, as long as I'll be able to get all the 
> information, based on one id. For example, if I have id=3, I want to get
> - name ('otherparent')
> - children (one child, with id=4, name='child')
> - parent id
>
> Any tips? Recipes? ;-)
>
>
> Thanks,
> Ksenia.

________________________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com




More information about the Python-list mailing list