【问题标题】:Printing values from dictionary从字典打印值
【发布时间】:2021-04-30 14:55:35
【问题描述】:

我在打印我制作的字典中的值时遇到问题。字典包含一个词作为键和对该词的描述作为值。我遇到的问题是应该打印用户输入的单词描述(查找)的函数没有按我想要的那样工作。

我已经实现了一个 for 循环来搜索用户想要在字典中查找的单词,然后打印该单词的描述(值)。它有点工作。问题是,例如,如果字典中有一个词:banana and apple 和描述:yellow and fruit。如果我想查找“苹果”,它将起作用。然后它会打印“苹果的描述:水果”。

如果我想查找“香蕉”的描述,就会出现问题。因为它是一个循环(我猜 word 的最新值是 apple)它会首先通过并打印“这个词不在字典中!”然后打印“香蕉描述:黄色”。所以我想解决这个问题,我应该实现另一种找到密钥的方法,而不是循环。我只是不知道怎么做。

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

【问题讨论】:

  • 而不是循环使用get。
  • 在这些情况下EAFP被认为是pythonic。
  • 字典功能不好

标签: python dictionary


【解决方案1】:

您只需要删除 else 条件并确保仅在循环结束时打印第二条语句(并且永远不会遇到中断部分)。

在当前版本的代码中,每次循环迭代都会执行条件条件,因此如果失败,它只会打印“未找到”。

这是一个例子:

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()

我还想补充一点,如果您的字典非常大,遍历字典中的所有值可能效率不高。 出于这个原因,我还想建议使用 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()

以下是我使用的 Get 方法的一些基本信息:

获取参数

get() 参数 get() 方法最多接受两个参数:

key - 要在字典中搜索的键值(可选) - 值 如果找不到密钥,则返回。默认值为无。返回 get() get() 方法返回的值:

如果键在字典中,则为指定键的值。没有,如果 未找到键且未指定值。如果键不是,则值 找到并指定了值。

获得回报

get() 方法的返回值 get() 方法返回:

如果键在字典中,则为指定键的值。没有,如果 未找到键且未指定值。如果键不是,则值 找到并指定了值。

更多关于 Python 字典的 get() 方法的信息可用here

【讨论】:

    【解决方案2】:

    Norie 说得对——这里有更多细节。你的功能:

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

    可以重写为使用 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!")
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2015-10-03
      • 2021-06-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多