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'
似乎当我遍历我的嵌套字典时,每个键数据类型都是字符串。任何解决方案来提取所需的值并将其分配给变量?
解决方案
快到了,就用这个:
lg_id = response_leagues[league]["league_id"]
而不是这个:
lg_id = league.key("league_id")
当我们遍历一个字典时,我们只遍历了键,而不是值,所以我们需要使用原始的dict来获取使用键的值。
发生错误是因为您试图调用一个字符串的方法 .key(),即 League_id 键。
推荐阅读
- pytorch - pytorch多机训练超时?
- algorithm - 容器中 X n 搜索的性能问题
- react-native - Android 11 上的展览位置权限处理问题
- python - 无法在 AWS 虚拟机上运行使用 Pyinstaller 创建的 .exe 文件
- verilog - EDAPlayground:Verilog 代码“达到最大运行时间”
- java - 如何使用 Mockito Junit 5 为 lambda 表达式创建 Junit 测试用例?
- macos - 使用 Qt 获取当前的 macOS shell
- python - 如何在条形图中显示第一个条形
- php - 我们如何在 Laravel 中更新/连接 whereHas 条件
- windows - 批量缺少操作数 errpr