Onat
Onat

Reputation: 801

How to append to a list in a dictionary?

Can I append to a list in a dictionary?

test = {'food' : 'apple'}

Is there a command to add 'banana' and turn it into

test = { 'food': ['apple','banana'] }

Thank you

Upvotes: 0

Views: 428

Answers (4)

Oleksi
Oleksi

Reputation: 13097

The simplest solution would just be to just make the value of your hash a list, that may contain just one element. Then for example, you might have something like this:

test = {'food' : ['apple']}
test['food'].append('banana')

Upvotes: 3

Adam Rosenfield
Adam Rosenfield

Reputation: 400174

I'd recommend using a defaultdict in this case, it's pretty straightforward to deal with dictionaries of lists, since then you don't need two separate cases every time you modify an entry:

import collections

test = collections.defaultdict(list)

test['food'].append('apple')
test['food'].append('banana')

print test
# defaultdict(<type 'list'>, {'food': ['apple', 'banana']})

Upvotes: 1

vz0
vz0

Reputation: 32923

You need to create a dict where the values are lists:

test = {'food' : ['apple']}
test['food'].append('banana')

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

No, since it isn't a list in the first place.

test['food'] = [test['food'], 'banana']

Upvotes: 5

Related Questions