我正在使用python 2编写英语词典。我创建了一个字典。例如," home"和"马"在词典中的关键。如果用户键入" ho"," home"和"马"将会来。我把这些放在底线。但是当用户选择单词1时,我想调用我首先设置的字典中的键和值。我该怎么办?
myEngDict = {"horse": "The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus","home": "the place where one lives permanently, especially as a member of a family or household."}
def Words():
word_List = []
count = 0
search_words = raw_input("Please enter a search term: ")
for i in myEngDict.keys():
if i.startswith(search_words):
count+=1
word_List.append(i)
print "{}{}{}".format(count,".", i)
else:
pass
choose = input("Which one?")
例如,如果" home"首先出来,用户选择1:
节目显示:
home: the place where one lives permanently, especially as a member of a family or household.
答案 0 :(得分:1)
首先,您应该在最后一行使用raw_input
。然后,您需要查找word_List
中提供的内容。
while True:
try:
choose = int(raw_input("Which one?"))
# Keep the key as a separate variable for faster reference
key = word_List[choose - 1]
# Use labels with the format function. It's easier to read and understand
print '{label}: {text}'.format(label=key, text=myEngDict[key])
# Be sure to have a break or return on success.
return
except ValueError:
# If someone provides 'cat', it will raise an error.
# Inform the user and go back to the start.
print 'Please provide an integer'
except IndexError:
# The user has provided a value above the length of word_List or
# less than one. Again, inform the user and go back to start.
print 'You must enter a number between 1 and {c}'.format(c=len(word_List))
答案 1 :(得分:0)
如果不改变你的代码,你可以在函数中以choose
之后的相同标识添加一个print语句:
print ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))