提取字典键的值并分配它

问题描述 投票:0回答:2

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

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'

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

python
2个回答
2
投票

几乎就在那里,只需使用:

lg_id = response_leagues[league]["league_id"]

而不是这个:

lg_id = league.key("league_id")

当我们遍历字典时,我们只遍历键而不是值,因此我们需要使用原始字典来使用键获取值。

您的错误发生是因为您尝试调用字符串的方法.key(),即联盟ID密钥。


0
投票

我发现这种方法更有用

def pars():
    leagues = neste_dictionary['api']['leagues']
    for id in nested_dictionary['api']['leagues']:
        lg_id = leagues[id]["league_id"]
        lg_name = leagues[id]["name"]
        lg_country = leagues[id]["country"])
        lg_logo = leagues[id]["logo"] 
        lg_season = leagues[id]["season"]
© www.soinside.com 2019 - 2024. All rights reserved.