Creating a structured list tree from a 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 read this post which generates a similar tree that I need, however this works with a symmetric set of nested list. I tried to use the groupby function of the list item, but could not create the list in the desired format. I believe there is something in python that is easy to do, which I don't see right now. Some pointers will be appreciated.

+4
source share
1 answer

If you can use only dict:

 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: {}}} 
+4
source

All Articles