【问题标题】:Python: Assigning user input as key in dictionary [closed]Python:将用户输入分配为字典中的键[关闭]
【发布时间】:2016-04-21 20:38:38
【问题描述】:

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

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

【问题讨论】:

标签: python python-3.x dictionary split tuples


【解决方案1】:

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

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:
    # ...

【讨论】:

    【解决方案2】:

    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")
      

    【讨论】:

    • 在没有解释的情况下转储代码对 OP 或未来的读者没有帮助。
    • @MorganThrapp 正在努力... :)
    【解决方案3】:

    我更改的每一行都有 cmets 来解释我所做的更改,但为了提高可读性,我也将它们放在这里。

    • 在第 2 行我实例化了一个字典 - 你以前是 为每一行重新定义一个字典
    • 在第 7 行,我更改了您的 将某些内容添加到字典中的代码,而不仅仅是创建一个 新的一个。这是正确的字典语法。
    • 在第 10 行,我更改了“如果 dict中的keyinput”到“如果dict.keys()中的keyinput”,因为你是 检查动物是否存在,以及文件中的动物 成为字典的键。

      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")
      

    【讨论】:

    • @MorganThrapp 我更改的每一行都有 cmets,你看到了吗?这不仅仅是代码转储。
    • @MorganThrapp 我不认为 Ian 只是在倾销代码,请删除您的反对意见
    【解决方案4】:

    首先,您不应将变量命名为与关键字相同的名称。其次,您将输入放入字典的方式将覆盖以前的值。您需要创建字典,然后添加新值。 第三,你输出值sound而不是从字典中得到它

    dict作为变量应该命名为mydict

    创建mydict = {} 在初始循环之前

    在第一个循环中设置mydict[animal] = sound

    mydict['dog'] = 'bark' # This is what happens
    

    如果在列表中,则打印keyinputmydict[keyinput]

    您也可以使用mysound = mydict.get(keyinput, "not in dictionary") 代替 if。

    Why dict.get(key) instead of dict[key]?

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2020-01-25
      • 2018-09-06
      相关资源
      最近更新 更多