繁体   English   中英

如何将输入值附加到字典中的列表?

[英]How to append an input value to a list in a dictionary?

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

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'

您可能想像这样使用它:

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

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

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

>>> 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' list可以append

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

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

我已经编写了以下代码,只要您在字典中已经有“ 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']}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM