提取字典键的值并分配

时间:2019-02-27 11:44:15

标签: python

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

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'

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

2 个答案:

答案 0 :(得分:2)

几乎在这里,只需使用此:

lg_id = response_leagues[league]["league_id"]

代替此:

lg_id = league.key("league_id")

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

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

答案 1 :(得分: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"]