Python KeyError異常的原因及問題解決
什么是 KeyError 異常?
在 Python 中,KeyError 異常是內置異常之一,具體來說,KeyError 是當試圖獲取字典中不存在的鍵時,引發(fā)的異常。作為參考,字典是一種將數(shù)據(jù)存儲在鍵值對中的數(shù)據(jù)結構,字典中的 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 時,也會遇到這樣的異常。例如,系統(tǒng)的環(huán)境變量。
# 獲取一個不存在的環(huán)境變量
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,并在出現(xiàn)錯誤時捕獲異常。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() 方式是一種容錯方法,但不是最優(yōu)解。
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異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Facebook開源一站式服務python時序利器Kats詳解
這篇文章主要為答案及介紹了Facebook開源一站式服務python時序利器Kats的功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11

