[英]Handling a keyerror with a python dictionary
How can I fix a KeyError
in a python dictionary?如何修复python字典中的
KeyError
?
I was asked to create a dictionary and create a function number_dictionary(text, n)
.我被要求创建一个字典并创建一个函数
number_dictionary(text, n)
。 I'm able to return True
or False
if the text
matches the n
, but there's a KeyError
when I put something that's not in the dictionary when it is supposed to return False
.我能够返回
True
或False
,如果text
的匹配n
,但有一个KeyError
,当我把东西时,它应该返回,这不是在字典False
。
I've put the two conditions together (when it does not match and not in the dictionary), but then it returns everything as False
.我已将这两个条件放在一起(当它不匹配且不在字典中时),但随后它将所有内容都返回为
False
。
def number_dictionary(text,n):
numbers={'two': '2', 'three': '3', 'four': '4'}
if n != numbers[text] or n or text not in numbers:
return(False)
else:
return(True)
Three options:三个选项:
try: foo = somedictionary[bar] except KeyError: return False
Use the dict.get()
method to return a default value instead, that default value defaults to None
:使用
dict.get()
方法返回一个默认值,该默认值默认为None
:
foo = somedictionary.get(bar) # return None if bar is not a key
Test for the key seperately:单独测试密钥:
if bar not in somedictionary: return False
In your case you tested for the key after trying to access it.在您的情况下,您在尝试访问密钥后对其进行了测试。 You could swap the test (dropping the
or n
):您可以交换测试(删除
or n
):
def number_dictionary(text, n):
numbers={'two': '2', 'three': '3', 'four': '4'}
return text not in numbers or n != numbers[text]
Or just use dict.get()
, the default None
will never match a string n
:或者只是使用
dict.get()
,默认None
永远不会匹配字符串n
:
def number_dictionary(text, n):
numbers = {'two': '2', 'three': '3', 'four': '4'}
return numbers.get(text) == n
Both the not in
and ==
comparison tests already produce either True
or False
, so there is no need to use if
and separate return
statements. not in
和==
比较测试都已经产生True
或False
,因此不需要使用if
和单独的return
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.