简体   繁体   中英

How to append an input value to a list in a dictionary?

I'm trying to append a value entered by the user to list in a dictionary, but it shows error:

AttributeError: 'str' object has no attribute 'append'

Can anyone find out the mistake?

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' object has no attribute 'append'

You may want to use it like so:

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

Because the function input returns a string which means dict["SomeKey"] is also a string which doesn't have the append function.

This trace back will help you to resolve your problem.

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

So the error is correct 'str' object has no attribute 'append' . append is available on list .

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

So if you want to keep Dict["SomeKey"] as a list , just change it like which you already did in your last line.

I have written following code and it works fine as long as you already have that "SomeKey" in dictionary and you are entering the user inputs in double quotes.

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']}

From the previous part of your example you set Dict["SomeKey"] to a string.

Let's say that you typed in "foo" for the entry in step 3 in your example, then Dict["SomeKey"].append("another_string") (I used "another_string" as the result of what you might have typed for the input). Then, this becomes "foo".append("another_string). But "foo", a string, does not have an .append() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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