【发布时间】: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