【发布时间】:2021-04-28 16:49:06
【问题描述】:
我正在尝试使用元组制作各种字典。这个想法是将一个单词及其描述存储在一个元组中。然后元组进入一个列表。之后,我应该能够通过键入我想要描述的单词来在字典中查找单词的含义。
我的问题是仅从列表中提取元组的描述部分,并仅根据用户想要查找的单词打印。我确实有一个似乎可以用来制作元组并将它们存储在列表中的函数,但我认为该函数也是错误的。
这是我所能达到的:
def tuples():
dictionary = []
while True:
print("\n--- Menu for dictionary ---\n Choose 1 to insert a word\n Choose 2 to lookup a word\n Choose 3 to quit\n")
answer = input("Write 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("What word would you like to add: ")
des = input("Type a description of that word: ")
info = (word, des)
dictionary.append(info)
def lookup(dictionary):
word = input("What word do you want to lookup: ")
place = dictionary.index(word)
print("\nDescription of", word,":", dictionary[place], "\n")
【问题讨论】:
-
为什么不直接使用没有元组的字典呢?如果您使用单词作为键,使用描述作为值,那么如果不需要元组列表,那不会解决您的问题,还是我遗漏了什么?
-
是的,字典是我的下一个任务。但是这个任务是专门用元组来解决问题的:)
标签: python dictionary tuples