[英]How to loop through nested Python dictionary
我有从 API 中提取的 json 数据,我将其转换为 python 字典
response = {
"api": {
"results": 4,
"leagues": {
"22": {
"league_id": "22",
"name": "Ligue 1",
"country": "France",
"season": "2017",
"season_start": "2017-08-04",
"season_end": "2018-05-19",
"logo": "https://www.api-football.com/public/leagues/22.svg",
"standings": true
},
"24": {
"league_id": "24",
"name": "Ligue 2",
"country": "France",
"season": "2017",
"season_start": "2017-07-28",
"season_end": "2018-05-11",
"logo": "https://www.api-football.com/public/leagues/24.png",
"standings": true
},
"157": {
"league_id": "157",
"name": "National",
"country": "France",
"season": "2017",
"season_start": "2017-08-04",
"season_end": "2018-05-11",
"logo": "https://www.api-football.com/public/leagues/157.png",
"standings": true
},
"206": {
"league_id": "206",
"name": "Feminine Division 1",
"country": "France",
"season": "2017",
"season_start": "2017-09-03",
"season_end": "2018-05-27",
"logo": "https://www.api-football.com/public/leagues/206.png",
"standings": true
}
}
}
}
现在我试图遍历这个嵌套字典我需要提取这个嵌套字典中所需数据的所有第三个字典键是“22”、“24”、“157”、“206”,以便更好地理解所需的字典是
"22": {
"league_id": "22",
"name": "Ligue 1",
"country": "France",
"season": "2017",
"season_start": "2017-08-04",
"season_end": "2018-05-19",
"logo": "https://www.api-football.com/public/leagues/22.svg",
"standings": true
}
我正在尝试通过此代码迭代它
for i in response["api"]["leagues"]["22"]
但我的问题是 API 可以返回任何数量的结果,我不知道所需数据的键。 如果我不知道所需数据的键,我如何遍历它
最佳方法可能取决于您在遍历条目时对数据进行的操作,但是:
response_leagues = response['api']['leagues']
仅限于你关心的东西。 然后注意
[league for league in response_leagues]
给出了这个字典中的键列表(在你的例子中是['22', '24', '157', '206']
)。
因此,遍历这些最低级别字典中的每个条目的一种方法是:
for league in response_leagues:
for x in response_leagues[league]:
#do something with x (the key)
# and response_leagues[league][x] (the value)
# for example:
print(league, x, response_leagues[league][x])
带输出:
22 league_id 22
22 name Ligue 1
22 country France
22 season 2017
22 season_start 2017-08-04
22 season_end 2018-05-19
22 logo https://www.api-football.com/public/leagues/22.svg
22 standings True 24 league_id 24
24 name Ligue 2
...
或者,您可以通过循环键值对(项目)来获得相同的结果:
for league in response_leagues:
for x in response_leagues[league].items():
#here x[0] is the key and x[1] is the value
print(league, x[0], x[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.