繁体   English   中英

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

[英]Python: How to append to existing key of a dictionary?

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

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']的新列表添加到游戏键列表?

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

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

您可以将值追加到现有键是使用列表的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'])

上面的语句将在myDict ['games']中添加“ Post3”和“ post 3 description”作为单独的参数

使用列表的append()操作。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM