小编Kit*_*tty的帖子

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")
Run Code Online (Sandbox Code Playgroud)

python dictionary split tuples python-3.x

-1
推荐指数
1
解决办法
1万
查看次数

标签 统计

dictionary ×1

python ×1

python-3.x ×1

split ×1

tuples ×1