遍历嵌套字典提取键值赋值时遇AttributeError问题求解
解决嵌套字典遍历提取值的问题
你碰到的这个AttributeError很典型——当你直接遍历一个字典的时候,默认拿到的是它的字符串类型的键(比如"22"、"24"这些),而不是对应的值,所以调用.key()方法肯定会报错,因为字符串根本没有这个属性。
下面给你两种实用的解决方案,能轻松提取你需要的字段并赋值给变量:
方法1:遍历键值对(同时获取键和对应字典)
如果需要用到那些"22"、"24"这类键,或者想明确键与值的对应关系,可以用字典的.items()方法,它会返回每个键值对的元组:
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"] # 遍历每个键值对,league_key是"22"这类键,league_data是对应的联赛字典 for league_key, league_data in response_leagues.items(): lg_id = league_data["league_id"] lg_name = league_data["name"] lg_country = league_data["country"] lg_season = league_data["season"] # 其他需要的字段都可以这样提取赋值 print(f"联赛ID: {lg_id}, 名称: {lg_name}, 国家: {lg_country}, 赛季: {lg_season}")
方法2:直接遍历值(只关心联赛数据)
如果不需要那些"22"、"24"的键,只需要提取联赛的具体信息,用.values()方法更直接,它会直接返回每个联赛对应的字典:
response_leagues = nested_dictionary["api"]["leagues"] # 直接拿到每个联赛的字典数据 for league_data in response_leagues.values(): lg_id = league_data["league_id"] lg_name = league_data["name"] print(f"ID: {lg_id} | 联赛名称: {lg_name}")
简单总结:你之前的代码错误在于把字典的键当成了字典本身,只要用.items()或.values()拿到真正的联赛字典数据,就能通过键名(比如"league_id")提取对应的数值赋值给变量了。
内容的提问来源于stack exchange,提问作者user8318311
相关产品推荐
相关产品推荐

