简体   繁体   English

从字典中打印值

[英]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.我遇到的问题是在 function 中,它应该打印用户输入的单词(查找)的描述,但它没有按我的意愿工作。

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.我已经实现了一个 for 循环来搜索用户想要在字典中查找的单词,然后打印该单词的描述(值)。 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.问题是,例如,如果字典中有一个词:banana and apple 和描述: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".因为它是一个循环(我猜单词的最新值是苹果),它首先会通过 go 并打印“字典中没有这个词:”,然后打印“香蕉的描述。黄色”。 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).您只需要删除 else 条件并确保仅在循环结束时打印第二条语句(并且永远不会遇到中断部分)。

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():出于这个原因,我还想建议使用 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 方法的一些基本信息:

Get Parameters获取参数

get() Parameters get() method takes maximum of two parameters: get() 参数 get() 方法最多接受两个参数:

key - key to be searched in the dictionary value (optional) - Value to be returned if the key is not found. key - 要在字典中搜索的键 value (可选) - 如果未找到该键则返回的值。 The default value is None.默认值为无。 Return Value from get() get() method returns: get() get() 方法的返回值返回:

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: get() get() 方法的返回值返回:

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 .有关 Python 字典的 get() 方法的更多信息,请点击此处

Norie has it right - here's a little more detail.诺里说得对——这里有更多细节。 Your function:您的 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:可以重写为使用 get 而不是遍历键:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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