【问题标题】:Python 3.8: Having difficulty with searching through nested lists and dictionariesPython 3.8:难以搜索嵌套列表和字典
【发布时间】: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')

非常感谢。 戴夫

【问题讨论】:

  • 你想提取什么?经纬度?
  • 我认为至少,您应该检查它是字典还是列表,而不是键而是值。
  • 您的递归甚至不会运行第二次,因为kstring(值为"Locations")。而且由于它不等于unitaryAuthArea,因此它不会在函数中打印任何内容。毕竟,检查这个问题:stackoverflow.com/q/10756427/4636715

标签: python list dictionary nested


【解决方案1】:

稍微改变了循环,检查 v 而不是 k。并循环 if 列表。

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(v, dict):
            print('\n V is a dictionary')
            nested_extract(v, key)
        if isinstance(v, list):
            print('\n V is a list')
            for elem in v:
                nested_extract(elem, 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')

【讨论】:

  • 谢谢,这很好用,因为它不受这个特定结构的限制。
【解决方案2】:

这是您要查找的内容,因为您说您想通过搜索“unitaryAuthArea”来获取位置列表?这仅在结构保持不变的情况下才有效。我在列表推导中添加了一个 if 语句,以确保您的关键字“unitaryAuthArea”不在字典中时不会出错。希望它可以帮助你。如果您正在寻找其他东西,请给我评论。

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'

results = [location['unitaryAuthArea'] for location in sites['Locations']['Location'] if location.get('unitaryAuthArea', False)]

print(results)
#output: ['Cumbria', 'Ceredigion', 'South Gloucestershire', 'Merseyside']

【讨论】:

    【解决方案3】:

    您应该按值而不是键进行迭代:

    if isinstance(v, dict):
          print('\n V is a dictionary')
          nested_extract(v, key)
    if isinstance(v, list):
          print('\n V is a list')
          if isinstance(v[0], dict):
               print('\n V is an Inner dictionary')
               nested_extract(v[0], key)
    

    然后不是[0] 遍历列表的每个值:

    if isinstance(v, dict):
        print('\n V is a dictionary')
        nested_extract(v, key)
    if isinstance(v, list):
        print('\n V is a list')
        for x in v:
            if isinstance(x, dict):
                print('\n X is an Inner dictionary')
                nested_extract(x, key)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多