简体   繁体   中英

How to append strings to a list in a dictionary

I have some trouble trying to append in a dictionary, I really dont know how to use it, because every time I try to run my code, Its says "'str' object has no attribute 'append'"... I have something like this...

oscars= {
'Best movie': ['The shape of water','Lady Bird','Dunkirk'],
'Best actress':['Meryl Streep','Frances McDormand'],
'Best actor': ['Gary Oldman','Denzel Washington']
}

so I want to make a new category, and then I want to make a cycle where the user can enter as many nominees as he want...

   newcategory=input("Enter new category: ")
   nominees=input("Enter a nominee: ")
   oscars[newcategory]=nominees
   addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))
   while addnewnominees!= "No":
       nominees=input("Enter new nominee: ")
       oscars[newcategory].append(nominees)
       addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))

Anyone knows how to use the append in dictionaries?

You cannot append to a string. Form a list first so you can append to it later:

oscars[newcategory] = [nominees]

As has been mentioned, if you create a key's value as a string, you can't use append on it, but you can if you make the key's value a list. Here is one way to do so:

newcategory=input("Enter new category: ")
oscars[newcategory]=[]
addnewnominees = 'yes'
while addnewnominees.lower() != "no":
    nominees=input("Enter new nominee: ")
    oscars[newcategory].append(nominees)
    addnewnominees = str(input("Do you want to enter more nominees: (yes/no):"))
newcategory=input("Enter new category: ")
nominees=input("Enter a nominee: ")
oscars[newcategory]= list()  
oscars[newcategory].append(nominees)
addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))
while addnewnominees!= "No":
    nominees=input("Enter new nominee: ")
    oscars[newcategory].append(nominees)
    addnewnominees= str(input("Do you want to enter more nominees: (yes/no):"))

Explanation:

When the input is passed as stdin the input is always a string . So at the line oscars[newcategory].append(nominees) it throw an error as the interpreter doesn't know that newcategory is a list, so first we need to define it as list by

oscars[newcategory]= list() 

And then we can append the nominees as many user want.

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