4

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.

4
  • What is the rule for nested list and nested dict? Commented Mar 16, 2013 at 12:06
  • @HYRY Item next in a list is a child of the item previous in the list. So in [2,5,6] 5 is a child of 2 and 6 is a child of 5. Basically I have to group the elements to form a tree like structure i.e. parent child relation. Commented Mar 16, 2013 at 12:12
  • Why the result is not like {1: {}, 2: {3: {}, 4: {}, 5: {8: {9: {}}, 6: {}, 7: {}}}, 11: {12: {}}, 10: {}} Commented Mar 16, 2013 at 12:14
  • @Dude According to your comment rule, you will have a forest (multiple trees) of degenerate trees (no branches). Additionally, I can't see any pattern that leads to the result you wrote. I'm not even sure what to ask here to clarify things. Commented Mar 16, 2013 at 12:27

1 Answer 1

4

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: {}}}
Sign up to request clarification or add additional context in comments.

1 Comment

I also have a nested list, I wonder if there is any way to build a tree with this anytree or treelib?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.