简体   繁体   English

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

[英]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'])

the above statement will add argument as a one value 上面的语句将参数作为一个值添加

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

the above statement will add 'Post3' and 'post 3 description' as an individual argument to myDict['games'] 上面的语句将在myDict ['games']中添加“ Post3”和“ 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.

相关问题 如何在循环中将第二个值附加到字典中的现有键 - How to Append a 2nd value to an existing key in a dictionary in Python in a Loop 如何将新键添加到现有字典并将前一个键作为值附加到 for 循环中创建的新键:python - How to add a new key to an existing dictionary and append previous key as value to the new key created in a for loop : python 使用Python中的现有或不存在的键将值追加到字典中的列表 - Append value to list in dictionary with existing or non-existing key in Python 如何在python字典中按值附加现有键? - How to append existing keys by value in python dictionary? 如何在Python字典中将字符串追加到现有值 - How to append string to existing values in Python dictionary 我如何将字典 append 作为现有字典键的另一个值 - How do I append a dictionary as another value to an existing dictionary key Python:将列表添加到分配给字典中键的现有列表吗? - Python: Append a list to an existing list assigned to a key in a dictionary? Append 元素到字典中的键,而不覆盖 Python 中的现有元素 - Append elements to a key in dictionary without overwriting the existing elements in Python 如何将值附加到 python 字典中的现有键? 在没有“”的循环中 - How can i append values to an existing key in a dictionary in python? in a loop without " " Python 字典 append 键? - Python dictionary append to key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM