I have a nested dictionary, and I am trying to write a function that will find matching keys, and return all the keys in the path to the key that matches. Given the example nested dictionary below:
nested_dict = {'a': {'b':{'c': 'd',
'e': 'f'},
'g': {'h': {'i': 'j'}}},
'k': {'l': 'm',
'n': 'o',
'p': {'q': 'r',
's': 't'}}}
I want the function getpath to return:
getpath(s) = ['k','p','s']
getpath(i) = ['a', 'g','h','i']
I wrote the recursive function below to try to accomplish this, but it's not returning anything, I'm hoping I'm close but am making a small error:
start_keys = list()
def getpath(nested_dict,search_value,keys):
# extract keys from the dict
dict_keys = list(nested_dict.keys())
# loop through dict keys
for key in dict_keys:
# append key to keys
keys.append(key)
level_down = nested_dict[key]
# check if the key matches the target value
if search_value.lower()==key.lower():
# if it does match, we're good, so return keys
return(keys)
else:
# since it didn't match, we attempt to go further down
if type(level_down) is dict:
# run getpath on it
getpath(level_down, search_value, keys)
else:
# if we can't go further down, it means we got to the end without finding a match, so we wipe out keys
keys = list()