ameliagunawan
ameliagunawan

Reputation: 23

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

Upvotes: 1

Views: 3571

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121764

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.

Upvotes: 8

Related Questions