简体   繁体   中英

dict of dicts python

I have a python dictionary consisting of other dictionaries like so (example):

{2: {4: {5: {6: {7: None}}}, 7: None}, 7: None}

I would like to extract the keys so that I end up with:

[2,4,5,6,7,None]
[2,7,None]
[7,None]

I have tried to solve this problem with a recursive function, however with no luck...

def f(d):
    paths = []
    try:
        for key in f.keys():
            path.append(f(d[key]))
    pass:
        pass

Is there a way to do this and how?

The following seems to do the trick:

def f(d):
    paths = []
    for key, value in d.items():
        if value is None:
            paths.append([key, value])
        else:
            internal_lists = f(value)
            for l in internal_lists:
                paths.append([key] + l)
    return paths

1) Your try: loop is badly written: the syntax is

try:
    xxx
except:
    xxx

And do you expect a failure here? Why the try?

2) Your loop can't be right neither:

for key in f.keys():

f is a function, it does not have keys. d does.

3) When dealing with a key, you need to keep it somewhere in the output, and you don't for the moment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM