简体   繁体   English

使用 python 字典处理 keyerror

[英]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 .我能够返回TrueFalse ,如果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:三个选项:

  • Catch the exception : 捕捉异常

     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==比较测试都已经产生TrueFalse ,因此不需要使用if和单独的return语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM