How to iterate through a nested dictionary to find a specific value given a list whose elements are keys?

73 Views Asked by At

I'm trying to write a function that accepts two parameters - a nested dictionary and a list whose elements are a subset of the keys (missing keys aren't considered). Using the list's elements, the function has to iterate over the dictionary to find and return the corresponding value. So, basically the list is the 'path' that the function uses to 'walk' through the dictionary to find the target value => def walk(dictionary, path). I can't use map, filter or reduce in my code. This is a coding task for a course I'm taking and my knowledge of Python is quite limited.

So, here is the test dictionary and lists (=path):

city = {
        'Pine': {
            '5': 'School #42',
        },
        'Elm': {
            '13': {
                '1': 'Appartments #2, Elm st.13',
            },
        },
    }
   
path = ['Elm', '13', '1']
path = ['Pine', '5']

And here's the function that I'm currently working on:

def walk(dictionary, path):
    key_select = getitem(path, len(path) - 1)

    for key, value in dictionary.items():
        if isinstance(value, dict):
            print(key)
            walk(value, path)
        else: 
            print(key)
        if key == key_select:
            print(value)
            
walk(city, path)

I get the 'correct' answer if I pass any of the two lists into the function, but there are a couple of problems: 1) I need to return a value (not print it) and when I try to do that I get "None"; and 2) I only need to return one value that corresponds to a specific key. My question then is, how can I modifiy the function so that it retains it's overall functionality (i.e. it iterates through the entire dictioanry) without all the extra stuff that it does. Thanks.

0

There are 0 best solutions below