Try and Except Exceptions with a Dictionary (Python)

Try and Except Exceptions with a Dictionary (Python)

Let's say I asked the user for a word, if the word is not a key in the dictionary, then I want to print "That word is not a key in the dictionary, try again". How would I do this using try and except? This is what I have so far.

dict = {"These": 1, "are": 2, "words": 3}
while True:
    try:
        w = input("Enter a word: ")
    except: 
        print("That word is not a key in the dictionary, try again")
    else:
        print("That word is a key in the dictionary")
4

3 Answers

You could catch the KeyError when accessing a key that doesn't exist in the map:

try:
    w = input("Enter a word: ")
    k[w]
except KeyError:
    print("That word is not a key in the dictionary, try again")
else:
    print("That word is a key in the dictionary")

To directly answer your question, this code does what you're looking for:

words = {"these": 1, "are": 2, "words": 3}
while True:
    try:
        value = words[input("Enter a word: ").trim().lower()]
    except KeyError: 
        print("That word is not a key in the dictionary, try again")
    else:
        print("That word is a key in the dictionary")

Couple important things to call out. Using except: without an Exception is very bad practice, as it will catch anything (like SystemExit or KeyboardInterrupt for instance, which will prevent your program from exiting correctly). dict is a name of a builtin function, so you are re-defining it by naming your dictionary dict.

As others suggested in the comments, you don't need try/except to do this unless you're trying to learn more about try/except. A better way to do this would be to use a set:

words = {"these", "are", "words"}
while True:
    if words[input("Enter a word: ").trim().lower()] in words:
        print("That word is a key in the dictionary")
    else:
        print("That word is not a key in the dictionary, try again")

You could also avoid using try/except blocks by using dict.get(), which returns the value mapped at the specified key, or None(default) if the key was not found. You can change this default to anything you want.

Code:

data = {"These": 1, "are": 2, "words": 3}

# make all keys lowercase
data = {k.lower(): v for k, v in data.items()}

while True:
    w = input("Enter a word: ")

    if data.get(w.lower()):
        print("That word is a key in the dictionary")
    else:
        print("That word is not a key in the dictionary, try again")

Output:

Enter a word: these
That word is a key in the dictionary
Enter a word: These
That word is a key in the dictionary
Enter a word: blah
That word is not a key in the dictionary, try again

Note: Keys above were converted to lowercase to avoid case insensitivity when looking up keys. You also shouldn't use dict as a variable name, since it shadows the reserved keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.