使用python遍历嵌套列表以获取特定值

时间:2019-05-16 16:31:37

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

我有一个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
      }

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

1 个答案:

答案 0 :(得分:1)

访问data['areas']这是一个列表,然后对其进行迭代以获取单个area对象

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

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