Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在dict中找到一个值?_Python_Dictionary_Find - Fatal编程技术网

Python 在dict中找到一个值?

Python 在dict中找到一个值?,python,dictionary,find,Python,Dictionary,Find,我正在打印一条信息。 如果在字典中找不到一个单词,那么它应该打印出一条消息,而不是给出一个错误。 我想的是 if bool(bool(dictionary[word])) == True: return dictionary[word] else: print 'wrong' 但当我写一些字典里没有的东西时,它就不起作用了,相反,它给出了这样的东西 Traceback (most recent call last): File "<pyshell#34>", l

我正在打印一条信息。 如果在字典中找不到一个单词,那么它应该打印出一条消息,而不是给出一个错误。 我想的是

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' 
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
翻译单词('hous')
文件“H:\IND104\final\Project 4-意大利语-西班牙语翻译人员\trial 1.py”,第21行,翻译为
如果bool(bool(字典[单词])==True:
KeyError:“hous”

因此,我如何打印错误消息,谢谢。

您需要使用中的
操作符来测试字典中是否有键。使用变量名,这将变成:

if word in dictionary:
如果您希望检查键的存在并一次性检索值,可以使用以下方法:

您可以将自己的默认值提供给
get()
,如果找不到键,将返回该值。然后您可以这样编写代码:

print dictionary.get(word, 'wrong')

实现所需功能的一种方法是使用
尝试
/
,但
块除外:

try:
    return dictionary[word]
except KeyError:
    print 'wrong'
    return None

为字典编制索引时,假定该键已存在,为了测试该键是否在字典中,请尝试以下操作:

#Check to see if a key is in a dictionary
dictionary = {'key' : 123}
if 'key' in dictionary:
 #Do something
else:
 #Do something else

[dictionary]中的[key]现在是比上一个has_key([key])dictionary方法更受欢迎的语法:

学习一些异常处理的时间到了:

try:
    some_stuff()
except:
    print "Sorry, an error occured"

您永远不应该执行
bool(bool(x))==True
。只是
x
。在我使用这一行之后,它还会继续阅读其余的行,在我使用这一行之后,我如何才能停止阅读其余的行?@Sarp这是另一个问题在我使用这一行之后,它还会继续阅读其余的行,在我使用这一行之后,我如何停止阅读其余的行?@SarpKaya:你是在循环中这样做的吗?然后使用
break
不是
也是运算符:
如果值不是None
@chepner对不起,我的Python不太流利!仅供参考:)这很奇怪,因为它是两个单词,需要特殊的语言支持。毕竟,你不能用其他任何东西来组合
not
(你不能说
not)
#Check to see if a key is in a dictionary
dictionary = {'key' : 123}
if 'key' in dictionary:
 #Do something
else:
 #Do something else
try:
    some_stuff()
except:
    print "Sorry, an error occured"