return all paths in a nested dictionary that also contains a list in python

24 Views Asked by At

First of all, I apologize for my poor English, I hope this question has been clearly stated.

I need a function that, when I call it, returns all possible paths of a nested dictionary that includes a list.

Example :

Input variable:

var={"a":"b","c":["d","e",{"f":"","h":["i",{"j":"q"} ]}],"m":"","n":["d","e",{"b":"","c":"","f":"r"}]," r":"r","k":["d","t","h"]} 

The output should look like this:

a/b 
c/d 
c/e 
c/f/ 
c/h/i 
c/h/j/q 
m/
n/d
n/e
n/b/
n/c/
n/f/r 
r/r 
k/d 
k/t 
k/h 

Notes :

It doesn't matter if the lines are printed in the order of the lines above, but the values of the lines must be the same as the lines above . Each path starts with the key of the outermost dictionary and ends when it can no longer be continued, that is, for example, we reach a dictionary value that is not a dictionary or a list, or we reach an item from a list, but if we reach a list or a dictionary, for example The path must continue

1

There are 1 best solutions below

2
Muhammed Samed Özmen On
def get_paths(d, path=''):
    paths = []
    for key, value in d.items():
        if isinstance(value, dict):
            paths.extend(get_paths(value, path + key + "/"))
        elif isinstance(value, list):
            for i, item in enumerate(value):
                if isinstance(item, dict) or isinstance(item, list):
                    paths.extend(get_paths(item, path + key + "/"))
                else:
                    paths.append(path + key + "/" + str(item))
        else:
            paths.append(path + key + "/" + str(value) if value else path + key + "/")
    return paths

var={"a":"b","c":["d","e",{"f":"","h":["i",{"j":"q"} ]}],"m":"","n":["d","e",{"b":"","c":"","f":"r"}]," r":"r","k":["d","t","h"]} 


paths = get_paths(var)
for path in paths:
    print(path)