映射是 Python 中的一种数据结构,它将一组值映射到另一组值。Python 字典是映射中使用最广泛的。每个值都有一个键,可以用来查看该值。当用于查找值的映射中不存在键时,会发生键错误。
在本文中,我们将讨论 Python keyerror 和 keyerror 处理及其示例。但是在讨论 Python keyerror 之前,我们先了解一下 Python 中的字典。
Python 中的字典
Python 中的字典(dict)是一个离散的值集合,包含相当于地图的存储数据值。它与其他数据类型的不同之处在于它只有一个元素,即一个值。它包含键和值对。因为键值,所以效率更高。A 冒号 表示键和值对的分隔,逗号表示每个键的分隔。这本 Python 字典的工作方式与普通字典相同。密钥必须是唯一的,由不可更改的数据类型组成,包括 字符串、整数、元组。
**例如:
让我们举个例子来理解我们如何在 python 中使用字典(dict)。
# A null Dictionary
Dict = {}
print("Null dict: ")
print(Dict)
# A Dictionary using Integers
Dict = {1: 'Hill', 2: 'And', 3: 'Mountin'}
print("nDictionary with the use of Integers: ")
print(Dict)
# A Dictionary using Mixed keys
Dict = {'Name': 'John', 1: [17, 43, 22, 51]}
print("nDictionary with the use of Mixed Keys: ")
print(Dict)
# A Dictionary using the dict() method
Dict = dict({1: 'London', 2: 'America', 3:'France'})
print("nDictionary with the use of dict(): ")
print(Dict)
# A Dictionary having each item as a Pair
Dict = dict([(1, 'Hello'), (2, 'World')])
print("nDictionary with each item as a pair: ")
print(Dict)
输出:执行完上面这段代码后,我们会得到如下所示的输出:
Null dict:
{}
nDictionary with the use of Integers:
{1: 'Hill', 2: 'And', 3: 'Mountin'}
nDictionary with the use of Mixed Keys:
{'Name': 'John', 1: [17, 43, 22, 51]}
nDictionary with the use of dict():
{1: 'London', 2: 'America', 3: 'France'}
nDictionary with each item as a pair:
{1: 'Hello', 2: 'World'}
Python 中的键错误
当我们试图从不存在的字典中访问一个键时,Python 会引发一个键错误。它是一个内置的异常类,由几个与 dicts 或包含键值对的对象交互的模块引发。现在,我们知道什么是 Python 字典以及它是如何工作的。让我们看看什么定义了键错误。每当我们想要访问不在 Python 字典中的键时,Python 都会引发一个键错误。
映射逻辑是一种将一段数据连接到其他重要数据的数据结构。因此,当访问映射但未找到时,会引发错误。这类似于查找错误,语义错误是我们寻找的密钥不在它的内存中。它在下面的例子中表现得更好。
例如:
让我们举一个例子来理解我们如何在 Python 中看到键错误。我们取键 A、B、C 和 D,其中 D 在 python 字典中是不存在的。尽管如此,字典中剩余的键正确地显示了输出,D 显示了键错误。
# Check the Keyerror
ages={'A':45,'B':51,'C':67}
print(ages['A'])
print(ages['B'])
print(ages['C'])
print(ages['D'])
输出:执行完上面这段代码后,我们会得到如下所示的输出:
45
51
67
Traceback (most recent call last):
File "", line 6, in <module>KeyError: 'D'</module>
Python 中一个关键错误的处理机制
任何遇到关键错误的人都能负责任地处理它。它可以检查特定程序的所有可能输入,并正确管理任何有风险的条目。当我们得到一个密钥错误时,有一些常规的方法来处理它。此外,一些方法可以用来处理键错误的机制。
通常的解决方案是:。get()方法
其中一些选项可能更好,也可能不是我们正在寻找的确切解决方案,这取决于我们的用例。然而,最终目标是防止意外的关键错误异常发生。例如,如果我们在自己的代码中从字典中获得一个错误,我们可以使用。get() 方法获取指定的键或默认值。
例如:
让我们举一个例子来理解我们如何处理 Python 中的键错误机制。
# List of vehicles and their prices.
vehicles = {"Car=": 300000, "Byke": 115000, "Bus": 250000}
vehicle = input("Get price for: ")
vehicle1 = vehicles.get(vehicle)
if vehicle1:
print("{vehicle} is {vehicle1} rupees.")
else:
print("{vehicle}'s cost is unknown.")
输出:执行完上面这段代码后,我们会得到如下所示的输出:
Get price for: Car
Car is 300000 rupees.
keyerror 的一般解决方案:try-except 方法
常见的方法是利用try-除了块,通过引发相关代码并提供备份解决方案来解决此类问题。
例如:
让我们举一个例子来理解我们如何对 keyerror 应用通用解决方案。
# Creating a dictionary to store items and prices
items = {"Pen" : "12", "Book" : "45", "Pencil" : "10"}
try:
print (items["Book"])
except:
print ("The items does not contain a record for this key.")
输出:执行完这段代码后,我们会得到如下所示的输出:
45
在这里我们看到,我们从这些物品中获得了这本书的价值。因此,如果我们想要打印项目中没有的任何其他键值,它将打印这个输出。
# Creating a dictionary to store items and prices
items = {"Pen" : "12", "Book" : "45", "Pencil" : "10"}
try:
print (items["Notebook"])
except:
print ("The items does not contain a record for this key.")
输出:执行完这段代码后,我们会得到如下所示的输出:
The items does not contain a record for this key.
结论
现在,我们了解了一些可能引发 Python key error 异常的常见场景,以及几种防止它们终止我们程序的优秀策略。下次我们遇到密钥错误时,我们会知道这很可能是由于字典密钥查找错误造成的。通过查看追溯的最后几行,我们可能会获得所有我们需要的信息,以找出问题来自哪里。
如果问题是在我们自己的代码中进行字典键查找,我们可以使用更安全的。get() 函数,带有默认返回值,而不是直接在字典上查询键。如果我们的代码没有导致这个问题,那么 try-except 块是我们调节代码流的最佳选择。
异常不一定很可怕。如果我们理解了程序回溯中呈现给我们的信息以及错误的根本原因,我们就可以利用这些方法来使我们的程序更加可预测地流动。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/294131.html