Galaxy S
Galaxy S

Reputation: 39

how do you append a list to a dictionary value in Python?

So if you have some dictionary like this

dictionary={}
dictionary['a']=1
dictionary['a']=2
print(dictionary)

this would print {'a':2} and replaces the 1 Is there any way I can add 2 to the key 'a' as a list ? I know i can do something this like:

dictionary['a']=[1,2]

but I don't want to do it like this. Essentially what i am asking is how can i add the new value to my key using a list instead of replacing the previous value. Appreciate the help!

Upvotes: 0

Views: 63

Answers (2)

ssp
ssp

Reputation: 1710

It would be worth considering using a defaultdict if every value in the dict is/will be a list:

from collections import defaultdict

d = defaultdict(list)

d['a'].append(1)
d['a'].append(2)

Upvotes: 1

MatthewProSkils
MatthewProSkils

Reputation: 380

dictionary = {}
dictionary['a'] = []
dictionary['a'].append(1)
dictionary['a'].append(2)
print(dictionary)

Upvotes: 1

Related Questions