簡體   English   中英

當密鑰不存在時,為什么我沒有收到密鑰錯誤?

[英]Why didn't I get a key error when the key does not exist?

假設我有一個空的字典。

test_dict = {}

我原來的代碼是這樣的。

x = input()
try:
    info = test_dict.get(x)

except:
    print("Key Does Not Exist!")

但它不會在我的控制台中引發 KeyError,而是返回 None。 我很確定我測試了它並且它可以工作,但是在我將 Spyder 從 4.1.2 更新到 4.1.5 之后,它不再工作了,我必須將代碼更改為:

x = input()
if x in test_dict.keys():
    info = test_dict.get(x)

else:
    print("Key Does Not Exist!")

為什么它返回 None 而不是 KeyError?

如果您不了解某些行為, help通常很有用。 在這種情況下,您可以執行以下操作:

test_dict = {}
help(test_dict.get)

意識到:

Help on built-in function get:

get(key, default=None, /) method of builtins.dict instance
    Return the value for key if key is in the dictionary, else default.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM