【问题标题】:How to append an input value to a list in a dictionary?如何将输入值附加到字典中的列表?
【发布时间】:2019-12-11 23:09:48
【问题描述】:

我正在尝试将用户输入的值附加到字典中,但它显示错误:

AttributeError: 'str' 对象没有属性 'append'

谁能找出错误?

Dict = {} # an empty dictionary to be filled later

Dict["SomeKey"] = []

Dict["SomeKey"] = input ("Enter a value: ") # it works

Dict["SomeKey"].append(input("Enter another value: ")) # This part gives me error !!!

AttributeError: 'str' 对象没有属性 'append'

【问题讨论】:

  • 这是给你的字符串...(input 返回一个字符串)

标签: python list dictionary input append


【解决方案1】:

你可能想这样使用它:

dict["SomeKey"] = [input ("Enter a value: ")]
dict["SomeKey"].append(input('Yet again...'))

因为函数input返回一个字符串,这意味着dict["SomeKey"]也是一个没有append函数的字符串。

【讨论】:

  • 但这会删除第一个输入数据...我需要将新输入的数据附加到前一个!
  • 编辑解释。
【解决方案2】:

此追溯将帮助您解决问题。

>>> Dict = {}
>>> Dict["SomeKey"] = []
>>> type(Dict["SomeKey"])
list
>>> Dict["SomeKey"] = input ("Enter a value: ")  # in here you are change `list` to `str`
Enter a value: 123
>>> type(Dict["SomeKey"])
str

所以错误是正确的'str' object has no attribute 'append'appendlist 上可用。

>>> 'append' in dir(str)
False
>>> 'append' in dir(list)
True

因此,如果您想将Dict["SomeKey"] 保留为list,只需像在上一行中所做的那样进行更改即可。

【讨论】:

    【解决方案3】:

    我已经编写了以下代码,只要您已经在字典中拥有“SomeKey”并且您在双引号中输入用户输入,它就可以正常工作。

    Dict = {}
    Dict["SomeKey"] = []
    Dict["SomeKey"].append(input("Enter another value:"))
    Dict["SomeKey"].append(input("Enter another value:"))
    print Dict
    
    O/P
    sankalp-  ~/Documents  python p.py                                                                                                            
     ✔  2027  00:59:30
    Enter another value:"SomeValue1"
    Enter another value:"Somevalue2"
    
    {'SomeKey': ['SomeValue1', 'Somevalue2']}
    

    【讨论】:

      【解决方案4】:

      在示例的上一部分中,您将 Dict["SomeKey"] 设置为字符串。

      假设您在示例的第 3 步中为条目输入了“foo”,然后是 Dict["SomeKey"].append("another_string")(我使用“another_string”作为您可能为输入输入的结果)。然后,这变成了 "foo".append("another_string)。但是 "foo",一个字符串,没有 .append() 方法。

      【讨论】:

        猜你喜欢
        • 2020-04-09
        • 2023-04-04
        • 2023-03-23
        • 2017-11-15
        • 1970-01-01
        • 2020-12-06
        • 2022-01-06
        • 2019-03-29
        相关资源
        最近更新 更多