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.
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.
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.
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").
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.
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 ..
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.
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']}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With