-1

Give an n-level nested dictionary, and a path (e.g. ['a', 'b', 'c', 'd'], how can I traverse a nested dictionary to see if the path completely exists in the dictionary or not?

If the path doesn't exist, I want to return None, otherwise I want to return the value associated with the file. I'm not quite sure why my function isn't working.

def verify_path(path, d):
    if len(path) == 0 : return
    if path[0] in d:
        return verify_path(path[1:], d[path[0]])
    else:
        return None

def main():
    d = {
        'a1': {
            'b1': { 'asdf.txt': 10 },
            'b2': {
                'c1': {'qwerty.pdf': 1},
            }
        },
        'a2': {'foo.bar': 99},
        'a3': {
            'b3': {
                'c2': {'img.heic': 100}, 
            },
        },
    }

    print(verify_path('/a2/foo.bar'.split('/'), d))
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

1 Answers1

1

You are not checking for a leaf node.

def verify_path(path, d):
    if len(path) == 0 : return
    if not path[0] in d:
        return None
    if isinstance(d,dict):
        return verify_path(path[1:], d[path[0]])
    else:
        return d[path[0]]
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30