Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a tree structure from a path name

This might be very simple, but I'm not sure what to do here. In Python, I want to go through a list like:

full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]

and get a dictionary with a kind of tree structure based on these labels, like this:

dictionary = {"A:{"A":["A", "B"], "C":["B"]},"B":{"B":["B]}} 

but I'm not sure how to do it. I realize that I need some nested for loops. I know about the split() function in Python.

like image 725
Ada Avatar asked Jul 07 '21 15:07

Ada


People also ask

How do you make a tree path?

Make your tree for every string in array. Just split path for '/' , check whether the node exists in your tree or not, if it exists then move on... otherwise create a new node and add this node in childrens of parent node. Iterate using recursion. Following is model for tree's node.

How do I print a directory tree in Python?

path. join(root, f) tree_printer('. ') This will print a list of all the directories in your tree first and the print the paths of all the files in the directory recursively.

How do I create a tree structure from a string?

Just split each path by its delimiter and then add them to a tree structure one by one. i.e. if 'x1' does not exist create this node, if it does exist go to it and check if there is a child 'x2' and so on... I'd make the tree one string at a time. Make an empty tree (which has a root node - I assume there could be a path like "x7/x8/x9").

How to create a hierarchy that includes the tree path?

So how do you get from the following table structure into a hierarchy that includes the Tree Path. You could do it by doing a self JOIN from the table back to itself, joining parent to id, which would work for 2 levels. Then to go to the third or fourth level, you would need to another one or two self JOINs to get those levels in.

How many parts of a tree can be in a path?

It works only under the assumptions: the name column has stored (in the first part) the actual "path". the depth of the tree is maximum 4 (so the path has up to 4 parts). the CAST ..

How do I get a table structure into a hierarchy?

So how do you get from the following table structure into a hierarchy that includes the Tree Path. You could do it by doing a self JOIN from the table back to itself, joining parent to id, which would work for 2 levels.


1 Answers

You can use recursion with collections.defaultdict:

from collections import defaultdict
def to_tree(data):
   d = defaultdict(list)
   for a, *b in data:
      d[a].append(b)
   return {a:[i for [i] in b] if all(len(i) == 1 for i in b) else to_tree(b)  
           for a, b in d.items()}

full_list = ["A/A/A", "A/A/B", "B/B/B", "A/C/B"]
result = to_tree([i.split('/') for i in full_list])

Output:

{'A': {'A': ['A', 'B'], 'C': ['B']}, 'B': {'B': ['B']}}
like image 162
Ajax1234 Avatar answered Oct 19 '22 13:10

Ajax1234