【问题标题】:Python: How to append to existing key of a dictionary?Python:如何附加到字典的现有键?
【发布时间】:2015-06-13 15:32:48
【问题描述】:

我有一本包含多维列表的字典,如下所示:

myDict = {'games':[ ['Post 1', 'Post 1 description'], ['Post2, 'desc2'] ], 'fiction':[ ['fic post1', 'p 1 fiction desc'], ['fic post2, 'p 2 fiction desc'] ]}

如何将带有 ['Post 3', 'post 3 description'] 的新列表添加到游戏密钥列表中?

【问题讨论】:

  • 只需将append 与索引一起使用!

标签: python dictionary key


【解决方案1】:

您要附加到值(在本例中为列表),而不是键。

myDict['games'].append(...)

【讨论】:

    【解决方案2】:
    myDict["games"].append(['Post 3', 'post 3 description'])
    

    【讨论】:

      【解决方案3】:

      您可以将值附加到现有键是使用列表的 append() 方法。

      dict[key].append(value)
      dict[key].extend(list of values)
      

      你可以这样写

      myDict['games'].append(['Post 3', 'post 3 description'])

      上述语句将参数添加为一个值

      myDict['games'].extend(['Post 3', 'post 3 description'])

      上述语句将添加 'Post3' 和 'post 3 description' 作为 myDict['games'] 的单独参数

      【讨论】:

        【解决方案4】:

        使用列表的append()操作。

        myDict['games'].append(['Post 3', 'post 3 description'])
        

        首先,您需要使用列表的dict[key] 查找来访问字典的'games' 键。然后您在games 键查找上获得的值是一个列表。
        然后使用append()操作将['Post 3', 'post 3 description']添加到games键里面的列表中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 2013-09-19
          • 2017-09-01
          • 2021-05-17
          • 2019-11-07
          • 1970-01-01
          • 2021-12-24
          相关资源
          最近更新 更多