【问题标题】:Python how to extend a list as if I was adding these items first timePython如何像我第一次添加这些项目一样扩展列表
【发布时间】:2017-11-09 07:35:03
【问题描述】:
question = []
question.append({'id' : 5, 'title' : 'First question', 'content' : 'Hi there'})

print("Question", question)

question.append({'username' : 'Ali'})

print("Question", question)

我想扩展一个列表,就好像我从 stratch 添加这些项目一样。打印语句的输出是:

问题 [{'id': 5, 'title': '第一个问题', 'content': 'Hi there'}, {'username': 'Ali'}]

我应该如何扩展列表以便打印语句输出:

问题 [{'id': 5, 'title': '第一个问题', 'content': 'Hi there', 'username': 'Ali'}]

更新: 在实际示例中,我尝试了三种方法。我收到了这些错误消息。

question[-1].update({'username' : 'Ali'})

AttributeError: 'dict' 对象属性 'update' 是只读的

(我之前也试过这个)

question["username"] = 'Ali'

TypeError: 列表索引必须是整数或切片,而不是 str

question[0]["username"] = 'Ali' 

工作正常。

【问题讨论】:

  • 如果将question.append({'username' : 'Ali'}) 替换为question[-1].update({'username' : 'Ali'}) 会发生什么?
  • 那么为什么你需要使用一个只包含一个项目的列表呢?
  • @CristiFati 感谢它有效。 Sraw 实际上我想向 MongoDB 添加一些记录,但我已经缩短了问一个问题。

标签: python python-3.x


【解决方案1】:

我用它来查询您的问题。不确定这是否能解决您的问题:

question = []
question.append({'id' : 5, 'title' : 'First question', 'content' : 'Hi there'})
question[0]["username"] = "test"
print question

输出:

[{'content': 'Hi there', 'username': 'test', 'id': 5, 'title': 'First question'}]

【讨论】:

    【解决方案2】:

    你有一个字典列表:

    dict_list = [{'foo': 'bar'}]
    

    您正在调用dict_list.append,它会将一个项目附加到列表中

    dict_list.append({'baz': 'bork'})
    print dict_list # => [{'foo': 'bar'}, {'baz': 'bork'}]
    

    如果你想更新原始字典,那么你应该检索那个特定的字典,然后更新它

    dict_list = [{'foo': 'bar'}]
    dict_list[0]['baz'] = 'bork' # we could also use dict_list[0].update here
    print dict_list # => [{'foo': 'bar', 'baz': 'bork'}]
    

    也就是说,您似乎正在尝试构建某种结构来保存这些问题以便于检索。与其使用列表,不如使用 dict-of-dicts 可能更明智,其中每个问题的关键是它的 id,例如:

    questions = {}
    questions[5] = {'title' : 'First question', 'content' : 'Hi there'}
    questions[5]['username'] = 'Ali'
    

    【讨论】:

      【解决方案3】:

      你可以试试:

      >>> question[0]["username"] = "Ali"
      >>> print(question)
      [{'username': 'Ali', 'id': 5, 'content': 'Hi there', 'title': 'First question'}]
      

      【讨论】:

        【解决方案4】:

        你正在做的是,实际上是在列表中添加一个字典。

        根据您在问题中提出的问题,您希望向该字典添加另一个变量,使其具有username 键。

        如果这就是你想要的,以下是更好的方法。

        question = {} #this will define the dictionary
        question['id'] = 5
        question['title'] = 'First question'
        question['content'] = 'Hi there'
        

        然后将 username 值添加到该字典中

        question['username'] = 'Ali'
        

        下一行也相当于前面代码的前4行

        question = {'id' : 5, 'title' : 'First question', 'content' : 'Hi there'}
        

        然后通过question['username'] = 'Aliusername键添加到字典中


        回答你的问题,(这似乎不是正确的做事方式)

        现在你有了一个包含单个元素的列表,它是字典,所以要向字典添加值,你需要引用列表的第一个元素,如下所示

        不要使用question.append({'username' : 'Ali'}),而是使用question[0]['username'] = 'Ali'

        您所做的实际上是向列表 question 添加了一个元素,因此输出就是您提到的内容。

        【讨论】:

          【解决方案5】:
          question = {'id' : 5, 'title' : 'First question', 'content' : 'Hi there'}
          # "extend" (=update the dictionary):
          
          question['username'] = 'Ali'
          

          【讨论】:

            【解决方案6】:

            您的目的是向您的 object 添加一个新字段,但您正试图将一个新元素 {'username' : 'Ali'} 添加到您的 questions 列表中。因此,您应该首先将字段 'username': 'Ali' 添加到您的对象中,然后将此对象添加到您的 questions 列表中。

            希望这会有所帮助:

            question = []
            your_object = {'id' : 5, 'title' : 'First question', 'content' : 'Hi there'}
            your_object['username'] = 'Ali'
            question.append(your_object)
            
            print("Question", question)
            

            【讨论】:

            • teşekkür ederim.
            • :) kolay gelsin hocam
            猜你喜欢
            • 1970-01-01
            • 2014-03-17
            • 1970-01-01
            • 2020-11-27
            • 1970-01-01
            • 2023-02-13
            • 2021-12-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多