Python: How to append to existing key of a dictionary?

25.8k Views Asked by At

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?

4

There are 4 best solutions below

0
On

You're appending to the value (which is a list in this case), not the key.

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

You can append value to existing key is to use append() method of list.

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

the above statement will add argument as a one value

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']

0
On

Use the append() operation of a list.

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. Then value you obtain on games key lookup is a list.
Then use the append() operation to add ['Post 3', 'post 3 description'] it to the list inside games key.