I am having problems printing values from a dictionary I made. The dictionary contains a word as a key and a description of that word as a value. The problem I run into is in the function that is supposed to print the description of a word (lookup) that the user puts in is not working as I want it to.
I have implemented a for loop to search for the word the user wants to look up in the dictionary and then print the description (value) of that word. and it kinda works. The problem is that if for example, the dictionary would have a word: banana and apple and description: yellow and fruit. It will work if I want to look up "apple". Then it will print "description of apple: fruit".
The problem appears if I then want to look up the description of "banana". Because it is a loop (and the latest value of word was apple I guess) it will first go through and print "the word is not in the dictionary!" and then print "description of banana: yellow". So I'm thinking to get past this problem I should implement another way of finding the key than a loop. I just don't know how.
def dictionary():
dictionary = {}
while True:
print("\n--- Menu for dictionary ---\n Choose 1 to insert a new word\n Choose 2 to find the description of a word\n Choose 3 to exit\n")
answer = input("Type your answer here: ")
if answer == "1":
insert(dictionary)
elif answer == "2":
lookup(dictionary)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(dictionary):
word = input("Type the word you want to add: ")
description = input("Type a description of the word: ")
if word in dictionary:
print("\nThe word already exists in the dictionary!\n")
return
else:
dictionary[word] = description
def lookup(dictionary):
wordsearch = input("What word would you like to lookup: ")
for word, description in ordlista.items():
if word == wordsearch:
print("\nDescription of", word,":", description)
break
else:
print("The word is not in the dictionary!")