I have a nested list like the following:
lst = [['a', 'b', 'e'], # this e is the branch of b
['a', 'f', 'e'], # this e is the branch of f,
['a', 'h', 'i i i']] # string with spaces
and I wanna to construct a tree like:
a
├── b
│ └── e
├── f
| └── e
└── h
└── i i i
I want to use either of the two packages: treelib and anytree. I've read many posts and tried many different methods and didn't make it work.
Update:
I came up with the following method, but the problems I have now are
- the vertical order of the branches (e.g., "b", "f", "h") is not guaranteed (when I have many lists in a list ).
- "e" as a branch of "f" won't show up
from treelib import Node, Tree
# make list flat
lst = sum([i for i in lst], [])
tree = Tree()
tree_dict = {}
# create root node
tree_dict[lst[0]] = tree.create_node(lst[0])
for index, item in enumerate(lst[1:], start=1):
if item not in tree_dict.keys():
partent_node = tree_dict[lst[index-1]]
tree_dict[item] = tree.create_node(item, parent=partent_node)
tree.show()