Kit*_*tty -1 python dictionary split tuples python-3.x
问题 我试图将用户输入分配为字典中的键.如果用户输入是键,则打印出其值,否则打印无效键.问题是键和值将来自文本文件.为简单起见,我将使用随机数据作为文本.任何帮助,将不胜感激.
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)
在循环的每次迭代中,您将重新定义字典,而是添加新条目:
d = {}
for i in file:
i = i.strip()
animal, sound = i.split(",")
d[animal] = sound
Run Code Online (Sandbox Code Playgroud)
然后,您可以按键访问字典项:
keyinput = input("Enter animal to know what it sounds like: ")
if keyinput in d:
print("The {key} {value}s".format(key=keyinput, value=d[keyinput]))
else:
print("The animal is not in the list")
Run Code Online (Sandbox Code Playgroud)
请注意,我还将字典变量名称从dictto 更改为d,因为它dict是一个糟糕的变量名称选择,因为它正在遮蔽内置dict函数.
此外,我改进了构建报告字符串的方式并改为使用字符串格式.如果你输入Dog,输出就是The Dog barks.
您还可以使用dict()构造函数在一行中初始化字典:
d = dict(line.strip().split(",") for line in file)
Run Code Online (Sandbox Code Playgroud)
作为旁注,要遵循最佳实践并保持代码的可移植性和可靠性,请在打开文件时使用with上下文管理器 - 它会正确关闭它:
with open("file.txt") as f:
# ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13750 次 |
| 最近记录: |