简体   繁体   中英

Printing values from dictionary

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

You just need to remove the else condition and make sure that you print the second statement only when the loop is over (and never hit the break part).

With the current version of your code that conditional is execute for every iteration of the loop so if it fails it just prints the "Not found".

Here's an example:

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 dictionary.items():
        if word == wordsearch:
            print("\nDescription of", word,":", description)
            break
    print("The word is not in the dictionary!")
            
            
dictionary()

I also want to add that looping through all the values in the dictionary may not be very efficient if your dictionary is very big. For this reason I'd like also to suggest another solution using using get():

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: ")
    if dictionary.get(wordsearch):
        print("\nDescription of", wordsearch,":", dictionary.get(wordsearch))
    else:
        print("The word is not in the dictionary!")
            
            
dictionary()

Here's some basic information the Get method I used:

Get Parameters

get() Parameters get() method takes maximum of two parameters:

key - key to be searched in the dictionary value (optional) - Value to be returned if the key is not found. The default value is None. Return Value from get() get() method returns:

the value for the specified key if key is in dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified.

Get returns

Return Value from get() get() method returns:

the value for the specified key if key is in dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified.

More information about the Python dictionary's get() method available here .

Norie has it right - here's a little more detail. Your function:

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

can be rewritten to use get instead of iterating through the keys:

def lookup(dictionary):
    wordsearch = input("What word would you like to lookup: ")
    look_result = ordlista.get(wordsearch)
    print(f"\nDecription of {word}: {look_result}" if look_result else "\nThe word is not in the dictionary!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM