嵌套字典的递归函数返回None,但是在函数中打印期望的数据

时间:2019-11-11 15:44:24

标签: python json python-3.x dictionary recursion

我有一个带有许多嵌套字典和列表的JSON,我需要修改它们,并且当我想查找数据时它没有返回结果。但是,它会在返回之前打印期望值。

下面是我需要使用的JSON简化结构:

nested_dict = {'k': {'component':'media','value':'It is a test'}}

我的下面的代码:

def find_component(data: object, component: str):
    """
    """
    if isinstance(data, list):
        for i, k in enumerate(data):
            find_component(data[i], component)
    if isinstance(data, dict):
        for k, v in data.items():

            if k == 'component' and v == component:
                print(k, v)
                print('Find Component', data)
                return data
            else:
                find_component(data[k], component)
# Call to the recursive function
res = find_component(nested_dict, 'media')

打印结果是预期结果:

component media
Find Component {'component': 'media', 'value': 'It is a test'}

但是数据结果为None

3 个答案:

答案 0 :(得分:1)

您需要return find_component。只需调用它,结果就会丢失,该函数返回None,因为这是任何未显式return值的函数都隐式返回的。

答案 1 :(得分:1)

您忘记了几个returns

def find_component(data: object, component: str):
    """
    """
    if isinstance(data, list):
        for i, k in enumerate(data):
            return find_component(data[i], component)
    if isinstance(data, dict):
        for k, v in data.items():
            if k == 'component' and v == component:
                print(k, v)
                print('Find Component', data)
                return data
            else:
                return find_component(data[k], component)

答案 2 :(得分:0)

基于@Joan Lara的回答,我找到了一个可行的解决方案。我需要检查结果是否不是None才能返回函数调用的结果,因此代码变为:

def find_component(data: object, component: str):
    """
    """
    if isinstance(data, list):
        for i, k in enumerate(data):

           res = find_component(data[i], component)
           if res is not None:
               return res
    if isinstance(data, dict):
        for k, v in data.items():

            if k == 'component' and v == component:
                print('I found the component', k, v)
                #print('Find Component', data)
                return data
            else:
                res = find_component(data[k], component)
                if res is not None:
                    return res