【问题标题】:How to append strings to a list in a dictionary如何将字符串附加到字典中的列表
【发布时间】:2018-09-25 16:25:17
【问题描述】:

我在尝试追加字典时遇到了一些麻烦,我真的不知道如何使用它,因为每次我尝试运行我的代码时,它都会说“'str' object has no attribute 'append'”...我有这样的东西......

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

所以我想创建一个新的类别,然后我想创建一个循环,用户可以输入任意数量的被提名者......

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

有谁知道如何在字典中使用追加?

【问题讨论】:

    标签: python string list dictionary append


    【解决方案1】:

    您不能附加到字符串。首先形成一个列表,以便您以后可以附加到它:

    oscars[newcategory] = [nominees]
    

    【讨论】:

    • 虽然在技术上不是追加,但使用my_string += "something to append"可以在字符串上获得相同的“追加”结果
    • @Julien,同意。但这称为字符串连接:)。字符串没有附加方法,但列表有。
    【解决方案2】:

    如前所述,如果将键的值创建为字符串,则不能在其上使用append,但如果将键的值设为列表,则可以。这是一种方法:

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

    【讨论】:

      【解决方案3】:
      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):"))
      

      解释:

      当输入作为标准输入传递时,输入总是string。所以在oscars[newcategory].append(nominees) 行它会抛出一个错误,因为解释器不知道newcategory 是一个列表,所以首先我们需要将它定义为列表

      oscars[newcategory]= list() 
      

      然后我们可以根据需要添加被提名者。

      【讨论】:

        猜你喜欢
        • 2020-12-06
        • 2018-09-13
        • 2012-12-05
        • 2020-04-09
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多