Dictionary to tree format (hopefully simple)

Adam Powell adtpowell at hotmail.com
Tue Aug 5 23:52:33 CEST 2008


Hi!
I have seemingly simple problem, which no doubt someone out there has
already solved, but I'm stumped. Imagine I have a dictionary like
below, in which the keys are parent nodes and the values are a list of
children nodes.

dict = { 0: [1, 2], 1: [3], 2: [6], 3: [4,7], 4: [5,8], 8: [9] }

Is there an obvious way to produce a nested tree format for this
dictionary, like this:

[ 0 [ 1 [ 3 [ 4 [ 5 , 8 [ 9 ] ] , 7 ] ] , 2 [ 6 ]  ]

Thanks for any help,

Adam



More information about the Python-list mailing list