[英]iterate through a nested list to get a specific value using python
I have a json file where I'm trying to pull just "code" from multiple "areas" 我有一个json文件,我试图从多个“区域”中仅提取“代码”
I am able to pull the codes individually, but I feel like there should be a for loop I can write to iterate over every 'area' automatically as I won't always just have 3 areas. 我可以单独提取代码,但是我觉得应该有一个for循环,我可以编写它以自动遍历每个“区域”,因为我不会总是只有3个区域。
I have tried multiple variations of the below nested loop but I just can't get it to iterate 我已经尝试了以下嵌套循环的多种变体,但我无法对其进行迭代
for areas in data:
for area in areas:
print(area['code']
Current python 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 file: 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
}
The expected results is that the 'code' prints out for each area. 预期结果是每个区域都会打印出“代码”。 Which it does correctly.
它正确地做到了。 However I want to iterate through it without having to add a new line every time as that's just ridiculous and tedious.
但是,我想遍历整个过程而不必每次都添加新行,因为那简直是荒谬而又乏味的。
Access data['areas']
which is a list, then iterate over it to get the individual area
objects 访问作为列表的
data['areas']
,然后对其进行迭代以获取各个area
对象
with open('areas.json') as f:
data = json.load(f)
for area in data['areas']:
print(area['area']['code'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.