在字典中查找值?
我正在尝试打印一条消息。 如果在字典中找不到某个单词,那么它应该打印出一条消息而不是给出错误。 我的想法是,
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'
那么我怎样才能打印出错误消息,谢谢。
I am trying to print out a message.
If a word in dictionary is not found then it should print out a message instead of giving an error.
What I thought is
if bool(bool(dictionary[word])) == True:
return dictionary[word]
else:
print 'wrong'
but it does not work when I write something that is not in dictionary instead it gives something like this
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'
So how can I print out an error message thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用
in
运算符来测试某个键是否在字典中。使用您的变量名称,这将变为:如果您希望一次性检查键是否存在并检索值,您可以使用
get()
方法:您可以向
get()
提供自己的默认值,如果 key没有找到。然后你可以像这样编写你的代码:You need to use the
in
operator to test whether or not a key is in the dictionary. With your variable names this becomes:If you wish to check for the presence of the key and retrieve the value in one go you can use the
get()
method:You can supply your own default value to
get()
which is returned if the key is not found. Then you could write your code like this:实现您想要的效果的一种方法是使用
try
/except
块:One way to achieve what you want is a
try
/except
block:索引字典假设键已经存在,为了测试键是否在字典中,请尝试以下操作:
[dictionary] 中的 [key] 现在是比之前的 has_key([key]) 字典方法更受欢迎的语法:参考
Indexing a dictionary assumes that the key is already there, in order to test if the key is in the dictionary, try this:
The [key] in [dictionary] is now the favoured syntax over the previous has_key([key]) dictionary method: reference
是时候学习一些异常处理了:
Time to learn some exception handling: