【发布时间】:2016-04-21 20:38:38
【问题描述】:
问题 我试图将用户输入分配为字典中的键。如果用户输入是键,则打印出它的值,否则打印无效键。问题是键和值将来自文本文件。为简单起见,我将只使用随机数据作为文本。任何帮助,将不胜感激。
文件.txt
狗,吠声
猫,喵
鸟儿,唧唧喳喳
代码
def main():
file = open("file.txt")
for i in file:
i = i.strip()
animal, sound = i.split(",")
dict = {animal : sound}
keyinput = input("Enter animal to know what it sounds like: ")
if keyinput in dict:
print("The ",keyinput,sound,"s")
else:
print("The animal is not in the list")
【问题讨论】:
-
你有什么问题?你应该阅读minimal reproducible example。
标签: python python-3.x dictionary split tuples