映射是 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/zh-tw/n/294131.html