alexcons
alexcons

Reputation: 531

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?

Upvotes: 2

Views: 26453

Answers (4)

pythondetective
pythondetective

Reputation: 336

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

Upvotes: 2

Rahul Gupta
Rahul Gupta

Reputation: 47906

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.

Upvotes: 0

Tuan Anh Hoang-Vu
Tuan Anh Hoang-Vu

Reputation: 1995

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

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799470

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

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

Upvotes: 7

Related Questions