問題 我試圖將用戶輸入指定爲字典中的鍵。如果用戶輸入是一個鍵然後打印出它的值,否則打印無效的鍵。問題在於鍵和值將來自文本文件。爲了簡單起見,我將使用隨機數據作爲文本。任何幫助,將不勝感激。Python:將用戶輸入指定爲字典中的鍵
file.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")
你的問題是?你應該閱讀[mcve]。 –