我正在尝试打印一条消息。 如果在字典中没有找到一个词,那么它应该打印出一条消息而不是给出错误。 我以为是
if bool(bool(dictionary[word])) == True:
return dictionary[word]
else:
print 'wrong'
但是当我写一些不在字典中的东西时它不起作用,而是给出这样的东西
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
translate_word('hous')
File "H:\IND104\final\Project 4 - Italian-Spanish Translator\trial 1.py", line 21, in translate_word
if bool(bool(dictionary[word])) == True:
KeyError: 'hous'
那么我怎样才能打印出错误信息呢,谢谢。
最佳答案
您需要使用in
运算符来测试某个键是否在字典中。使用您的变量名,这将变为:
if word in dictionary:
如果您希望一次性检查 key 是否存在并检索值,您可以使用 get()
方法:
value = dictionary.get(word)
if value is not None:
...
您可以向 get()
提供您自己的默认值,如果未找到 key ,则返回默认值。然后你可以这样写你的代码:
print dictionary.get(word, 'wrong')
关于python - 在字典中找到一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8917068/