[英]Python: How to append to existing key of a dictionary?
I have a dictionary with multidimensional lists, like so: 我有一本包含多维列表的字典,如下所示:
myDict = {'games':[ ['Post 1', 'Post 1 description'], ['Post2, 'desc2'] ], 'fiction':[ ['fic post1', 'p 1 fiction desc'], ['fic post2, 'p 2 fiction desc'] ]}
How would I add a new list with ['Post 3', 'post 3 description'] to the games key list? 如何将带有['Post 3','post 3 description']的新列表添加到游戏键列表?
您将附加值(在这种情况下为列表),而不是键。
myDict['games'].append(...)
myDict["games"].append(['Post 3', 'post 3 description'])
You can append value to existing key is to use append() method of list. 您可以将值追加到现有键是使用列表的append()方法。
dict[key].append(value)
dict[key].extend(list of values)
In your case you can write like this 在你的情况下,你可以这样写
myDict['games'].append(['Post 3', 'post 3 description']) myDict ['games']。append(['Post 3','post 3 description'])
myDict['games'].extend(['Post 3', 'post 3 description']) myDict ['games']。extend(['Post 3','post 3 description'])
Use the append() operation of a list. 使用列表的append()操作。
myDict['games'].append(['Post 3', 'post 3 description'])
First you need to access the 'games'
key of the dictionary using the dict[key]
lookup which is a list. 首先,您需要使用
dict[key]
查找(列表)来访问字典的'games'
键。 Then value you obtain on games
key lookup is a list. 然后,您在
games
按键查找中获得的值就是一个列表。
Then use the append()
operation to add ['Post 3', 'post 3 description']
it to the list inside games
key. 然后使用
append()
操作将['Post 3', 'post 3 description']
到games
键内的列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.