Python:将用户输入分配为字典中的键

新手上路,请多包涵

问题 我试图将用户输入指定为字典中的键。如果用户输入是一个键,则打印出它的值,否则打印无效键。问题是键和值将来自文本文件。为简单起见,我将只对文本使用随机数据。任何帮助,将不胜感激。

文件.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")

原文由 Kitty 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 397
2 个回答

在循环的每次迭代中,您都在 重新定义 dictionary ,而是添加新条目:

 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

此外,我还改进了构建报告字符串的方式并改为使用 字符串格式。如果您输入 Dog ,输出将为 The Dog barks


您还可以使用 dict() 构造函数在一行中初始化字典:

 d = dict(line.strip().split(",") for line in file)

作为旁注, 为了遵循最佳实践并保持代码的可移植性和可靠性,请在打开文件时使用 with 上下文管理器- 它会注意正确关闭它:

 with open("file.txt") as f:
    # ...

原文由 alecxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

OP,我在代码中写了一些冗长的解释性注释并修复了一些问题;我可能忽略了一些东西,但请检查一下。

  • 首先,避免使用 dict 作为变量名,因为它隐藏了 Python 的内置 dict 方法。
  • 请记住,在大多数情况下,您需要在循环之前声明变量,以便在循环 之后 可以访问它们;这适用于你的字典。
  • 此外,请记住在读取/写入后关闭文件,除非您使用 with open(filename) ...
   def main():
      # declare a new, empty dictionary to hold your animal species and sounds.
      # Note that I'm avoiding the use of "dict" as a variable name since it
      # shadows/overrides the built-in method
      animal_dict = {}
      file = open("file.txt")
      for i in file:
          i = i.strip()
          animal, sound = i.split(",")
          animal_dict[animal] = sound

      # Remember to close your files after reading
      file.close()

      keyinput = input("Enter animal to know what it sounds like: ")
      if keyinput in animal_dict:

          # here, keyinput is the string/key and to do a lookup
          # in the dictionary, you use brackets.
          # animal_dict[keyinput] thus returns the sound

          print("The ",keyinput,animal_dict[keyinput],"s")
      else:
          print("The animal is not in the list")

原文由 jDo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题