user3230395
user3230395

Reputation: 11

How to remove key error when looking up a definition in a dictionary?

I am relatively new to python or even programming in general so go easy on me (I'm sure this is a two line fix)

anyways I am supposed to write a program that has a hardcoded dictionary that a user can edit via a menu system. Everything is working perfectly except for when someone tried to look up, replace, or delete a word and does not enter a word that is already in the dictionary! How can I change my code so that when they enter something not in the dictionary it just puts them through the loop and asks them to try again?

dic={'1':"Steam",'2':"word",'3':"spotify",'4':"smite"}    
menu=int(input("what would you like to do")   
if menu==2:
    print(dic[input("what do you want to look up")])

Thank you for your time on answering my super basic question!

Upvotes: 1

Views: 319

Answers (1)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14955

This way:

dic={'1':"Steam",'2':"word",'3':"spotify",'4':"smite"}  
while True:
    menu = raw_input("what would you like to do: ")                                                                                                                                   
    if menu in dic:
         break

Just use an infinite loop until an option matchs a dict key.

Upvotes: 1

Related Questions