【问题标题】:iterate through a nested list to get a specific value using python使用python遍历嵌套列表以获取特定值
【发布时间】:2019-05-16 16:31:37
【问题描述】:

我有一个 json 文件,我试图从多个“区域”中提取“代码”

我可以单独提取代码,但我觉得应该有一个 for 循环我可以编写来自动迭代每个“区域”,因为我不会总是只有 3 个区域。

我尝试了以下嵌套循环的多种变体,但我无法让它迭代

for areas in data:
   for area in areas:
      print(area['code']

当前python代码:

import json

with open('areas.json') as f:
    data = json.load(f)


    print(data['areas'][0]['area']['code'])
    print(data['areas'][1]['area']['code'])
    print(data['areas'][2]['area']['code'])

JSON 文件:

"areas": [
      {
         "slotId": "slot1",
         "area": {
            "id": "southern",
            "code": "southern",
            "label": "southern area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      },
      {
         "slotId": "slot2",
         "area": {
            "id": "easter",
            "code": "eastern",
            "label": "eastern area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      },
      {
         "slotId": "slot3",
         "area": {
            "id": "western",
            "code": "western",
            "label": "western area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      }

预期结果是为每个区域打印出“代码”。它正确地做到了。但是,我想遍历它,而不必每次都添加新行,因为这既荒谬又乏味。

【问题讨论】:

    标签: python json python-3.x list dictionary


    【解决方案1】:

    访问 data['areas'] 这是一个列表,然后遍历它以获取单个 area 对象

    with open('areas.json') as f:
        data = json.load(f)
    
        for area in data['areas']:
            print(area['area']['code'])
    

    【讨论】:

    • 所以我修改了我的代码,现在我得到一个 KeyError: 'area'。它声明我在第 8 行得到它,对我来说这将是上面的打印语句 ``` print(area['area']['code']) ```
    • 根据您的示例,您的每个对象都应该有 area 键。或许,事实并非如此?
    • 上面的代码是正确的,我有一个错字。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2012-11-11
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多