【发布时间】:2020-07-09 08:57:51
【问题描述】:
我通过 API 访问数据,最终得到嵌套字典和列表中的数据。
我正在尝试通过在这组嵌套数据中搜索“unitaryAuthArea”来获取位置列表。
我得到的唯一结果是: 网站是一本字典。
Python 3.8
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_sites, key):
for k, v in nested_sites.items():
if isinstance(k, dict):
print('\n K is a dictionary')
nested_extract(k,key)
if isinstance(k, list):
print('\n K is a list')
if isinstance([0], dict):
print('\n K is an Inner dictionary')
nested_extract([0],key)
if k == key:
print(v)
if isinstance(sites, dict):
print('\n Sites is a dictionary')
nested_extract(sites,srch)
else:
print('\n Sites is NOT a dictionary')
非常感谢。 戴夫
【问题讨论】:
-
你想提取什么?经纬度?
-
我认为至少,您应该检查它是字典还是列表,而不是键而是值。
-
您的递归甚至不会运行第二次,因为
k是string(值为"Locations")。而且由于它不等于unitaryAuthArea,因此它不会在函数中打印任何内容。毕竟,检查这个问题:stackoverflow.com/q/10756427/4636715
标签: python list dictionary nested