Search code examples
pythonloopsdictionaryfor-loopwhile-loop

How to create all paths possible from a python dictionary?


I have a python dictionary where I'd like to output all possible paths from all key values. Here is a small scale example to visualize what I'm trying to do.

dictionary = {'parent':['child1','child2'], ‘child1’: ['child1_1','child1_2'], ‘child2’: ['child2_1','child2_2'], ‘child3’: [], 'child1_1'= ['child1_1_1', 'child1_1_2'], 'child1_1_1': [], 'child1_1_2': [], 'child1_2': [], 'child2_1': [], 'child2_2': [], 'child4'=[]}

And the output that I'd like to have is something like this:

parent/child1

parent/child1/child1_1

parent/child1/child1_1/child1_1_1

parent/child1/child1_1/child1_1_2

parent/child1/child1_2

parent/child2/child2_1

parent/child2/child2_2

parent/child3

parent/child4

.

.

.

Please note that I'd like to use it for a larger scale, so using 2 for loops I was able to output a path with parent and a 2 direct childs of it. But it doesn't work on larger scale, I think I need a for loop inside of a while true loop where I can check if a child doesn't have any childs of itself and it outputs me “Hey I'm the last one left and here is paths that are available to me" etc.

Thanks in advance and have a nice day.


Solution

  • child3 and child4 are not mentioned in the parent, so how do you want to point to parent in the output, if we ignore that the function that gives you desired output is this:

    def get_paths(dictionary, parent="", paths=None):
        if paths is None:
            paths = []
    
        paths.append(parent)
    
        if parent in dictionary:
            children = dictionary[parent]
            for child in children:
                child_paths = get_paths(dictionary, child)
                paths.extend([f"{parent}/{path}" for path in child_paths])
    
        return paths
    
    
    dictionary = {
        'parent': ['child1', 'child2'],
        'child1': ['child1_1', 'child1_2'],
        'child2': ['child2_1', 'child2_2'],
        'child3': [],
        'child1_1': ['child1_1_1', 'child1_1_2'],
        'child1_1_1': [],
        'child1_1_2': [],
        'child1_2': [],
        'child2_1': [],
        'child2_2': [],
        'child4': [],
    }
    
    paths = get_paths(dictionary, 'parent')
    
    for path in paths:
        print(path)
    

    Output:

    parent
    parent/child1
    parent/child1/child1_1
    parent/child1/child1_1/child1_1_1
    parent/child1/child1_1/child1_1_2
    parent/child1/child1_2
    parent/child2
    parent/child2/child2_1
    parent/child2/child2_2