Python调用API获取字典数据时KeyError处理及get方法使用问题
KeyError问题原因分析
- 最开始的
get方法用法完全错误:data.get(element['guest_operating_system']['version']['full_version'])是错误写法,get是字典实例的方法,应该由你要取值的字典对象调用,传入要获取的键名,而不是把多层字典取值的结果作为参数传给其他字典的get方法。 - 你修改后的代码逻辑错误:直接用
elemento['guest_operating_system']访问字典键时,如果键不存在就会直接抛出KeyError,根本不会执行后续的if判断。 - 判断条件逻辑完全错误:你要判断的是
'guest_operating_system'这个键是否存在于当前遍历的elemento字典中,而不是判断elemento['guest_operating_system']的值是否存在于data['vm']列表中。
正确解决方案
方式1:嵌套使用字典get方法(最推荐,写法简洁)
字典的get方法可以在键不存在时返回指定的默认值,不会抛出异常,多层嵌套字典要每一层都用get,避免某一层缺失导致报错:
version = elemento.get('guest_operating_system', {}).get('version', {}).get('full_version', 'Dato no disponible')
代码说明:
- 如果
elemento里没有guest_operating_system键,就返回空字典{}给下一层get调用 - 同理如果
guest_operating_system里没有version键,也返回空字典 - 最后如果找不到
full_version键,就返回默认值Dato no disponible
方式2:先逐层判断键是否存在
如果你习惯用if判断,要先检查每一层的键是否存在,再访问值:
if 'guest_operating_system' in elemento \ and 'version' in elemento['guest_operating_system'] \ and 'full_version' in elemento['guest_operating_system']['version']: version = elemento['guest_operating_system']['version']['full_version'] else: version = "Dato no disponible"
方式3:用try-except捕获异常
如果多层嵌套层级很深,直接捕获KeyError更简洁,只要任意一层键缺失就走分支返回默认值:
try: version = elemento['guest_operating_system']['version']['full_version'] except KeyError: version = "Dato no disponible"
完整可运行的修改后代码
import requests from requests.auth import HTTPBasicAuth # 禁用SSL警告,避免控制台输出冗余告警 requests.packages.urllib3.disable_warnings() # 注意原代码URL缺少字符串引号,此处已修正 URL = "https://api/ovirt-engine/api/vms" response = requests.get(URL, verify=False, auth = HTTPBasicAuth('admin@internal','password'), headers={'Accept': 'application/json'}) data = response.json() for elemento in data['vm']: name_vm = elemento['name'] descripcion = elemento['description'] # 嵌套get方法获取version version = elemento.get('guest_operating_system', {}).get('version', {}).get('full_version', 'Dato no disponible') print(f"vM: {name_vm}\nDescripción: {descripcion}\nVersión: {version}\n")
内容的提问来源于stack exchange,提问作者Santiago Valencia
相关产品推荐
相关产品推荐

