Skip to content Skip to sidebar Skip to footer

Handling A Keyerror With A Python Dictionary

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 m

Solution 1:

Three options:

  • Catch the exception:

    try:
         foo = somedictionary[bar]
    except KeyError:
         returnFalse
  • 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):

defnumber_dictionary(text, n):
    numbers={'two': '2', 'three': '3', 'four': '4'}
    return text notin 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.

Post a Comment for "Handling A Keyerror With A Python Dictionary"