首页 > 解决方案 > Python递归函数匹配键值并返回嵌套字典中的路径

问题描述

我有一个嵌套字典,我正在尝试编写一个函数来查找匹配的键,并将路径中的所有键返回到匹配的键。给定下面的示例嵌套字典:

nested_dict = {'a': {'b':{'c': 'd',
                      'e': 'f'},
                 'g': {'h': {'i': 'j'}}},
           'k': {'l': 'm',
                 'n': 'o',
                 'p': {'q': 'r',
                       's': 't'}}}

我希望函数 getpath 返回:

getpath(s) = ['k','p','s']
getpath(i) = ['a', 'g','h','i']

我在下面编写了递归函数来尝试完成此操作,但它没有返回任何内容,我希望我很接近但我犯了一个小错误:

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()

标签: pythonjsondictionaryrecursionnested

解决方案


您可以通过仅检查当前键是否匹配来简化递归search_value,如果关联的值为 a dict,则在这种情况下递归:

def getpath(nested_dict, search_value):
    # loop through dict keys
    for key in nested_dict.keys():
        # have we found the search value?
        if key == search_value:
            return [key]
        # if not, search deeper if this value is a dict
        if type(nested_dict[key]) is dict:
            path = getpath(nested_dict[key], search_value)
            if path is not None:
                return [key] + path
    # no match found in this part of the dict
    return None


getpath(nested_dict,'s')     # ['k','p','s']
getpath(nested_dict, 'i')    # ['a', 'g','h','i']

推荐阅读