什么是 keyerror 异常?
在 python 中,keyerror 异常是内置异常之一,具体来说,keyerror 是当试图获取字典中不存在的键时,引发的异常。作为参考,字典是一种将数据存储在键值对中的数据结构,字典中的 value 是通过其 key 获取的。
python keyerror 常见原因及示例
以国家及其首都的字典作为例子:
dictionary_capitals = {'beijing': 'china', 'madrid': 'spain', 'lisboa': 'portugal', 'london': 'united kingdom'}
要在字典中搜索信息,需要在括号中指定 key,python 将返回相关的 value。
dictionary_capitals['beijing']
'china'
如果获取一个在字典中没有的 key,python 将会抛出 keyerror 异常错误信息。
dictionary_capitals['rome']
traceback (most recent call last):
file "<stdin>", line 1, in <module>
keyerror: 'rome'
尝试获取其他 python 字典中不存在的 key 时,也会遇到这样的异常。例如,系统的环境变量。
# 获取一个不存在的环境变量 os.environ['users'] traceback (most recent call last): file "<stdin>", line 1, in <module> file "/library/frameworks/python.framework/versions/3.9/lib/python3.9/os.py", line 679, in __getitem__ raise keyerror(key) from none keyerror: 'users'
处理 python keyerror 异常
有两种策略去处理 keyerror 异常 ,一是避免 keyerror,二是捕获 keyerror。
防止 keyerror
如果尝试获取不存在的 key 时,python 会抛出 keyerror。为了防止这种情况,可以使用 .get() 获取字典中的键,使用此方法遇到不存在的 key,python 将会返回 none 而不是 keyerror。
print(dictionary_capitals.get('prague'))
none
或者,可以在获取 key 之前检查它是否存在,这种防止异常的方法被称为 “look before you leap”,简称 lbyl, 在这种情况下,可以使用 if 语句来检查键是否存在,如果不存在,则在 else 子句中处理。
capital = "prague" if capital in dictionary_capitals.keys(): value = dictionary_capitals[capital] else: print("the key {} is not present in the dictionary".format(capital))
通过异常处理捕获 keyerror
第二种方法被称为 “easier to ask forgiveness than permission”,简称 eafp,是 python 中处理异常的标准方法。
采用 eafp 编码风格意味着假设存在有效的 key,并在出现错误时捕获异常。lbyl 方法依赖于 if/else 语句,eafp 依赖于 try/except 语句。
下面示例,不检查 key 是否存在,而是尝试获取所需的 key。如果由于某种原因,该 key 不存在,那么只需捕获 except 子句中的 keyerror 进行处理。
capital = "prague" try: value = dictionary_capitals[capital] except keyerror: print("the key {} is not present in the dictionary".format(capital))
python 高阶处理 keyerror
使用 defaultdict
python 在获取字典中不存在的 key 时,会返回 keyerror 异常。.get() 方式是一种容错方法,但不是最优解。
collections 模块提供了一种处理字典更好的方法。与标准字典不同,defaultdict 获取不存在的 key ,则会抛出一个指定的默认值,
from collections import defaultdict # defining the dict capitals = defaultdict(lambda: "the key doesn't exist") capitals['madrid'] = 'spain' capitals['lisboa'] = 'portugal' print(capitals['madrid']) print(capitals['lisboa']) print(capitals['ankara'])
spain
portugal
the key doesn't exist
到此这篇关于python keyerror异常的原因及问题解决的文章就介绍到这了,更多相关python keyerror异常内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论