问题 我试图将用户输入分配为字典中的键。如果用户输入是键,则打印出其值,否则打印无效键。问题是键和值将来自文本文件。为简单起见,我将使用随机数据作为文本。任何帮助,将不胜感激。
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")
答案 0 :(得分:6)
在循环的每次迭代中,您都重新定义字典,而是添加新条目:
d = {}
for i in file:
i = i.strip()
animal, sound = i.split(",")
d[animal] = sound
然后,您可以按键访问字典项目:
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")
请注意,我还将字典变量名从dict
更改为d
,因为dict
是一个糟糕的变量名选择,因为它遮蔽了内置dict
此外,我改进了构建报告字符串的方式,并改为使用string formatting。如果您输入Dog
,则输出为The Dog barks
。
您还可以使用dict()
构造函数在一行中初始化字典:
d = dict(line.strip().split(",") for line in file)
作为附注,to follow the best practices and keep your code portable and reliable,在打开文件时使用with
context manager - 它会关注正确关闭它:
with open("file.txt") as f:
# ...
答案 1 :(得分:2)
urls.py
作为变量名称,因为它会影响Python的bult-in dict
方法。 此外,请记住在读/写后关闭文件,除非您使用dict
with open(filename) ...
答案 2 :(得分:1)
每行都有评论我改变了一些东西,解释了我改变了什么,但为了帮助提高可读性,我也将它们放在这里。
在第10行,我改变了#34;如果 键盘中的键输入"到"如果在dict.keys()"中键入输入,那么你就是这样 检查动物是否存在,以及文件中的动物 成为字典的关键。
def main():
dict = {} #Create an empty dictionary to add to
file = open("file.txt")
for i in file:
i = i.strip()
animal, sound = i.split(",")
dict[animal] = sound #This is how you add a key/value pair to a dictionary in Python
keyinput = input("Enter animal to know what it sounds like: ")
if keyinput in dict.keys(): #Add .keys() to iterate through dictionary keys
print("The ",keyinput,sound,"s")
else:
print("The animal is not in the list")
答案 3 :(得分:1)
首先,您不应将变量命名为与关键字相同。其次,将输入放入字典的方式将覆盖以前的值。您需要创建字典,然后添加新值。
第三,输出值sound
而不从字典中获取
dict
作为变量应命名为mydict
在初始循环之前创建mydict = {}
在第一个循环中设置mydict[animal] = sound
mydict['dog'] = 'bark' # This is what happens
打印keyinput
和mydict[keyinput]
,如果它在列表中。
您也可以使用mysound = mydict.get(keyinput, "not in dictionary")
代替if。