![](/img/trans.png)
[英]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.