[英]Iterate through nested Dictionary Object and get the value of specific object in Python
[英]iterate through a nested list to get a specific value using python
我有一个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
}
预期结果是每个区域都会打印出“代码”。 它正确地做到了。 但是,我想遍历整个过程而不必每次都添加新行,因为那简直是荒谬而又乏味的。
访问作为列表的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.