首页 > 解决方案 > 提取字典键的值并分配它

问题描述

我想遍历嵌套字典并将一些字典键值分配给变量。这是我的嵌套字典:

nested_dictionary = {

    "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
              }
            }
          }
        }

我尝试这种方法

response_leagues = nested_dictionary["api"]["leagues"]

for league in response_leagues:
        lg_id = league.key("league_id")
        print(lg_id)

但我的league.key()函数返回以下错误

AttributeError: 'str' object has no attribute 'key'

似乎当我遍历我的嵌套字典时,每个键数据类型都是字符串。任何解决方案来提取所需的值并将其分配给变量?

标签: python

解决方案


快到了,就用这个:

lg_id = response_leagues[league]["league_id"]

而不是这个:

lg_id = league.key("league_id")

当我们遍历一个字典时,我们只遍历了键,而不是值,所以我们需要使用原始的dict来获取使用键的值。

发生错误是因为您试图调用一个字符串的方法 .key(),即 League_id 键。


推荐阅读