Reputation: 137
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
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