Sar*_*aya 2 python dictionary find
我正在尝试打印出一条消息.如果找不到字典中的单词,那么它应该打印出一条消息而不是给出错误.我的想法是什么
if bool(bool(dictionary[word])) == True:
return dictionary[word]
else:
print 'wrong'
Run Code Online (Sandbox Code Playgroud)
但是当我写一些不在字典中的东西时,它不起作用,而是它给出了类似的东西
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'
Run Code Online (Sandbox Code Playgroud)
那么如何打印出错误信息谢谢.
Dav*_*nan 10
您需要使用in运算符来测试密钥是否在字典中.使用您的变量名称,这将成为:
if word in dictionary:
Run Code Online (Sandbox Code Playgroud)
如果您想检查是否存在密钥并一次性检索该值,您可以使用以下get()方法:
value = dictionary.get(word)
if value is not None:
...
Run Code Online (Sandbox Code Playgroud)
get()如果找不到密钥,您可以提供自己的默认值.然后你可以这样写你的代码:
print dictionary.get(word, 'wrong')
Run Code Online (Sandbox Code Playgroud)