Rahul
Rahul

Reputation: 137

Creating tree structured list from nested list

I have a nested list:

l = [[1], [2,3], [2,4], [2,5], [2,5,6], [2,5,7], [2,5,8],[2,5,8,9], [10],[11,12]]

and I need the list to be in a tree structured nested list, for example:

l = [{1:[], 2:[3,4,{5: [6,7, {8: [9]}]}], 10: [], 11: [12]}]

I have gone through this post which generates a similar tree that I need, however that works with symmetric set of nested list. I have tried using groupby feature of the list item but could not generate a list in desired format. I suppose there is something in python to do it easily which I am currently missing. Some pointers will be appreciated.

Upvotes: 4

Views: 3726

Answers (1)

HYRY
HYRY

Reputation: 97331

If you can use dict only:

l = [[1], [2,3], [2,4], [2,5], [2,5,6], [2,5,7], [2,5,8],[2,5,8,9], [10],[11,12]]
root = {}
for path in l:
    parent = root
    for n in path:
        parent = parent.setdefault(n, {})
import pprint
pprint.pprint(root, width=1)

output:

{1: {},
 2: {3: {},
     4: {},
     5: {6: {},
         7: {},
         8: {9: {}}}},
 10: {},
 11: {12: {}}}

Upvotes: 4

Related Questions