1

How can I fix a KeyError in a python dictionary?

I was asked to create a dictionary and create a function 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.

I've put the two conditions together (when it does not match and not in the dictionary), but then it returns everything as 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)
1

1 Answer 1

8

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:

    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):

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:

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I would put .get() the first and try .. except the last.
@IgorPomaranskiy: Why would that be? Both are valid options, neither has a clear advantage in general. It depends on how frequently the key is missing which option is faster, for example. In other words: it depends on the specific code and the typical frequencies of the keys being probed.
Thank you so much!! It fixed the problem :) there's actually a test for a hidden input do you know what that is?
@ameliagunawan: no idea what that might be; perhaps you could ask that in a new question? Don't forget to include a minimal reproducible example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.