Python 3.8嵌套数据查询问题:提取unitaryAuthArea字段失败
解决嵌套字典与列表中提取指定字段的问题
嘿Dave,我看了你写的提取unitaryAuthArea字段的代码,问题出在几个关键逻辑上,导致没法正确遍历嵌套结构拿到目标数据。咱们来一步步梳理并修正:
原代码的核心问题
- 你在遍历字典的时候,错误地判断**键(k)的类型,而实际上应该检查值(v)**的类型——毕竟嵌套的字典/列表都是作为值存在的
- 处理列表的逻辑完全错误:
isinstance([0], dict)是在判断一个包含0的列表是不是字典(这永远是False),而且没有遍历列表中的每个元素 - 找到匹配字段时只是打印,没有收集结果,没法得到完整的地区列表
修正后的代码
sites={'Locations': {'Location':[{'elevation': '50.0', 'id': '14', 'latitude': '54.9375', 'longitude': '-2.8092', 'name': 'Carlisle Airport', 'region': 'nw', 'unitaryAuthArea': 'Cumbria'},{'elevation': '108.0', 'id': '355874', 'latitude': '52.415775', 'longitude': '-4.059387', 'name': 'Penglais School', 'region': 'wl', 'unitaryAuthArea': 'Ceredigion'},{'elevation': '75.0', 'id': '3930', 'latitude': '51.55138', 'longitude': '-2.55933', 'name': 'Almondsbury', 'region': 'sw', 'unitaryAuthArea': 'South Gloucestershire'},{'elevation': '22.0', 'id': '26', 'latitude': '53.3336', 'longitude': '-2.85', 'name': 'Liverpool John Lennon Airport', 'region': 'nw', 'unitaryAuthArea': 'Merseyside'}]}} srch='unitaryAuthArea' def nested_extract(nested_data, key): results = [] if isinstance(nested_data, dict): for k, v in nested_data.items(): if k == key: results.append(v) # 递归处理值的嵌套结构 results.extend(nested_extract(v, key)) elif isinstance(nested_data, list): # 遍历列表中的每个元素,递归处理 for item in nested_data: results.extend(nested_extract(item, key)) return results # 调用函数并输出结果 area_list = nested_extract(sites, srch) print(area_list)
代码说明
- 收集结果:用一个列表
results来存储找到的所有匹配值,最后返回这个列表,方便后续使用 - 正确判断类型:
- 如果当前数据是字典,遍历键值对,若键匹配则添加值到结果,然后递归处理值的内容
- 如果当前数据是列表,遍历每个元素并递归处理,把每个元素的结果合并到总列表
- 递归逻辑:不管是字典还是列表,只要有嵌套就继续深入遍历,确保不会漏掉任何层级的目标字段
运行这段代码后,你会得到预期的地区列表:
['Cumbria', 'Ceredigion', 'South Gloucestershire', 'Merseyside']
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

