0

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

jamylak
  • 128,818
  • 30
  • 231
  • 230
Onat
  • 771
  • 1
  • 11
  • 17

4 Answers4

5

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

test['food'] = [test['food'], 'banana']
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

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

test = {'food' : ['apple']}
test['food'].append('banana')
vz0
  • 32,345
  • 7
  • 44
  • 77
3

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')
jamylak
  • 128,818
  • 30
  • 231
  • 230
Oleksi
  • 12,947
  • 4
  • 56
  • 80
1

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']})
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • It is straightforward to do this without a `defaultdict` too: `test.setdefault("food", []).append("apple")` – kindall May 14 '12 at 05:12