检查密钥是否在字典中并且在相同的"if"安全中获取它的值?

Ily*_*rov 5 python dictionary python-3.x

我认为这是安全的:

if key in test_dict:
    if test_dict[key] == 'spam':
        print('Spam detected!')
Run Code Online (Sandbox Code Playgroud)

但这样安全吗?

if key in test_dict and test_dict[key] == 'spam':
    print('Spam detected!')
Run Code Online (Sandbox Code Playgroud)

它应该做同样的事情因为条件检查在python中是懒惰的.它不会尝试获取值(并引发异常,因为dict中没有这样的键)因为第一个条件已经不满足.但我可以依靠懒惰并在我的程序中使用第二个例子吗?

Ana*_*mar 13

是的,它是安全的,如果第一个表达式结果为False,Python会短路,也就是说它不会评估if条件中的第二个表达式.

但更好的方法是使用.get(),None如果字典中没有键,则返回.示例 -

if test_dict.get(key) == 'spam':
    print('Spam detected!')
Run Code Online (Sandbox Code Playgroud)

  • 它不相同 - 垃圾邮件密钥可能具有值'无'. (4认同)