【问题标题】:Why didn't I get a key error when the key does not exist?为什么当密钥不存在时我没有收到密钥错误?
【发布时间】:2020-10-27 08:33:08
【问题描述】:

假设我有一个空字典。

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?

【问题讨论】:

  • 因为你使用了.get。这就是它应该要做的事情,它与您的IDE 更新无关。另外:1.永远不要使用裸except:,具体说明你正在捕捉什么(在这种情况下except KeyError); 2.你可以用x in test_dict来测试字典的成员资格;和 3. 如果你在 test_dict[x] 中缺少密钥,你会得到一个密钥错误。
  • Tq 告诉我 1. 和 2. 但是当我 dict.get(一个不存在的键) 时它确实返回 NoneType
  • 是的,我明白;通过使用 您明确要求的 get 方法
  • 哦.. 我现在没有看到 test_dict[x] juz。好的。 Tqvm
  • 所以当我在不存在的键上使用 get 方法时不会得到 KeyError?

标签: python dictionary spyder nonetype keyerror


【解决方案1】:

如果您不了解某些行为,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.

【讨论】:

  • 谢谢。我现在明白了,我也学到了一个新功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多