解决 Python 中 KeyError 0 异常
每种编程语言都会遇到很多错误。 有些发生在编译时,有些发生在运行时。
KeyError
是一种运行时错误,其中代码语法正确,但在代码执行过程中会抛出错误。
Python 中的 KeyError 0 异常
当我们尝试访问的映射键 0 未定义时,Python 运行时会出现 KeyError 0
。 映射键将抛出 KeyError 0
异常。
映射是一种数据结构,通过冒号 : 将一个值映射到另一个值。 字典是最常见的映射类型。
在下面的示例中,字典中仅定义了三个键及其对应的学生姓名。 如果我们尝试访问字典中的任何其他键,它将抛出 KeyError。
示例代码:
#Python 3.x
dict = {1: 'kelvin', 2:'Ron' , 3:'James'}
print(dict[0])
输出:
这里,当我们访问字典中的键 0 时,会生成 KeyError 0
,因为键 0 不存在。
有多种方法可以解决 Python 中的 KeyError 0
。 以下是一些方法及其解释和代码。
使用 try-except 块解决 Python 中的 KeyError 0
在这个例子中, dict 中没有定义 0,但它不会给出 KeyError 0 异常,因为 try- except 块会处理它。 它不会打印错误,而是在异常块中打印一条语句。
示例代码:
#Python 3.x
dict={3:'Kelvin',5:'James',6:'Danial'}
try:
print(dict[0])
except KeyError:
print('key not present in the dictionary')
输出:
#Python 3.x
key not present in the dictionary
使用 dict.get() 解决 Python 中的 KeyError 0
get()
方法有效地处理 KeyError。 使用 get()
,我们可以返回字典中不存在的键的默认值或消息。
在这个例子中,key 0 不存在,所以会打印默认的 set 语句:key 0 does not exist in dictionary。 如果我们不提供默认值,该方法将返回 None。
示例代码:
#Python 3.x
dict={3:'Kelvin',5:'James',6:'Danial'}
print(dict.get(0, 'key 0 does not exist in dictionary'))
输出:
#Python 3.x
key 0 does not Exist in dictionary
使用 if-else 解决 Python 中的 KeyError 0
在访问键 0 之前,我们可以使用 for 循环和 if-else 语句检查该键是否存在于字典中,如示例所示。 它只会根据键打印字典中的值。
示例代码:
#Python 3.x
dict={3:'Kelvin',5:'James',6:'Danial'}
for i in range(1,7):
if i in dict:
print(dict[i])
else:
continue
输出:
#Python 3.x
Kelvin
James
Danial
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串