如何检查含嵌套结构的字典中是否存在None值
检查嵌套字典/列表中是否存在None值
要处理这种结构不固定、可能嵌套字典或含字典列表的情况,最直接的方式是用递归遍历,碰到None就立刻返回存在,否则继续深入嵌套结构。
实现代码
def has_none_value(data): # 当前元素是None,直接返回存在 if data is None: return True # 遍历字典的所有值 if isinstance(data, dict): for value in data.values(): if has_none_value(value): return True # 遍历列表/元组的元素(排除字符串,避免拆成单个字符检查) elif isinstance(data, (list, tuple)): for item in data: if has_none_value(item): return True # 其他类型(字符串、数字等)直接返回不存在 return False
测试示例字典
拿你提供的示例数据测试:
sample_data = { "first_name": "test", "last_name": "test", "cars": [ {"mark": "test", "type": "12"}, {"mark": "test2", "type": "7"}, ], "date_created": "2022-05-07", "invoice_info": { "price": 1233, "currency": "EUR", "date": [ {"date_1": "2022-05-07", "info": {"comment": "test", "place": "France"}}, {"date_2": "2022-06-12", "info": {"comment": None, "place": "France"}}, ] } } print(has_none_value(sample_data)) # 输出: True
代码逻辑说明
- 优先判断当前元素是否为None,是则直接返回True;
- 遇到字典时,递归检查每个键对应的值;
- 遇到列表/元组时,递归检查每个元素;
- 字符串、数字等非嵌套类型直接返回False;
- 只要在任意嵌套层级找到None,函数立刻终止遍历返回结果,避免不必要的计算。
内容的提问来源于stack exchange,提问作者marwen aydi
相关产品推荐
相关产品推荐

