Python:如何附加到字典的现有键?

时间:2015-06-13 15:32:49

标签: python dictionary key

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

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']的新列表?

4 个答案:

答案 0 :(得分:5)

您附加了值(在这种情况下是列表),而不是键。

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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您可以将值附加到现有密钥是使用list的append()方法。

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

在你的情况下你可以像这样写

myDict ['游戏']。追加(['发布3','发布3说明'])

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

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

上述声明将添加' Post3'和'发布3描述'作为myDict [' games']

的个人参数

答案 3 :(得分:0)

使用列表的 append()操作。

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

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