在嵌套字典中查找无值的位置

时间:2022-09-28 19:29:48

I need to identify any None values in a potentially deeply-nested dictionary, which can also contain lists. Below is my code as it exists now. It works, but it only returns the name of the key directly associated with the None value.

我需要在可能深度嵌套的字典中识别任何None值,该字典也可以包含列表。下面是我现在存在的代码。它可以工作,但它只返回与None值直接相关的键的名称。

I want to have the whole list of keys pointing to the None
(e.g. nested["top_key"]["next_key"]["final_key"])

我希望将整个键列表指向None(例如嵌套[“top_key”] [“next_key”] [“final_key”])

def search_for_None(nested):
    for key, value in nested.items():
        if isinstance(value, dict):
            search_for_None(value)
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    search_for_None(item)
        else:
            if value is None:
                logging.error("Missing value for key '{0}'".format(key))

1 个解决方案

#1


0  

You need to pass the path along with the recursive call. Something like below

您需要传递路径以及递归调用。像下面的东西

def search_for_None(nested, path):
    for key, value in nested.items():
        dict_path = f"{path}[{key!r}]"
        if isinstance(value, dict):
            search_for_None(value, dict_path)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                list_path = f"{dict_path}[{index!r}]"
                if isinstance(item, dict):
                    search_for_None(item, list_path)
        else:
            if value is None:
                logging.error("Missing value for key '{0}'".format(dict_path))

The path parameter should be a string (e.g. "nested")

path参数应该是一个字符串(例如“嵌套”)

Also, note that the code you posted (and mine) will not find a None value in a list (e.g. {"a": [None]}) as there's no check for that condition.

另请注意,您发布的代码(以及我的代码)将不会在列表中找到None值(例如{“a”:[None]}),因为没有检查该条件。

#1


0  

You need to pass the path along with the recursive call. Something like below

您需要传递路径以及递归调用。像下面的东西

def search_for_None(nested, path):
    for key, value in nested.items():
        dict_path = f"{path}[{key!r}]"
        if isinstance(value, dict):
            search_for_None(value, dict_path)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                list_path = f"{dict_path}[{index!r}]"
                if isinstance(item, dict):
                    search_for_None(item, list_path)
        else:
            if value is None:
                logging.error("Missing value for key '{0}'".format(dict_path))

The path parameter should be a string (e.g. "nested")

path参数应该是一个字符串(例如“嵌套”)

Also, note that the code you posted (and mine) will not find a None value in a list (e.g. {"a": [None]}) as there's no check for that condition.

另请注意,您发布的代码(以及我的代码)将不会在列表中找到None值(例如{“a”:[None]}),因为没有检查该条件。