简体   繁体   English

如何遍历嵌套的 Python 字典

[英]How to loop through nested Python dictionary

I have json data extracted from API I converted it to 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
          }
        }
      }
    }

Now I am trying to iterate through this nested dictionary I need to extract all third dictionaries inside this nested dictionary keys of needed data are "22", "24", "157", "206" for better understanding needed dictionary is现在我试图遍历这个嵌套字典我需要提取这个嵌套字典中所需数据的所有第三个字典键是“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
              }

i am trying to iterate through it by this code我正在尝试通过此代码迭代它

for i in response["api"]["leagues"]["22"] 

but my issue that API can return any quantity of results and i didnt know keys of needed data.但我的问题是 API 可以返回任何数量的结果,我不知道所需数据的键。 how i can iterate through it if i didnt know keys of needed data如果我不知道所需数据的键,我如何遍历它

The optimal approach could depend on exactly what you are doing with the data as you iterate through the entries, but:最佳方法可能取决于您在遍历条目时对数据进行的操作,但是:

response_leagues = response['api']['leagues']

restricts to just the stuff you care about.仅限于你关心的东西。 Then note that然后注意

[league for league in response_leagues]

gives a list of the keys in this dictionary (in your example this is ['22', '24', '157', '206'] ).给出了这个字典中的列表(在你的例子中是['22', '24', '157', '206'] )。

So one way to loop through each of the entries in these lowest level dicts is:因此,遍历这些最低级别字典中的每个条目的一种方法是:

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])

with output:带输出:

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 
...

Alternatively, you can get the same result by looping over the key-value pairs (items):或者,您可以通过循环键值对(项目)来获得相同的结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM