20

When using Python is it possible that a dict can have a value that is a list?

for example, a dictionary that would look like the following (see KeyName3's values):

{
keyName1 : value1,
keyName2: value2,
keyName3: {val1, val2, val3}
}

I already know that I can use 'defaultdict' however single values are (understandably) returned as a list.

The reason I ask is that my code must be generic so that the caller can retieve single key values as an item (just like from a dict key-value) and not as list (without having to specify pop[0] the list) - however also retrieve multiple values as a list.

If not then any suugestions would be welcome.

If someone can help then that would be great.

Thanks in Advance,

Paul

*I'm using Python 2.6 however writing scripts that must also be forward compatible with Python 3.0+.

Marcin
  • 48,559
  • 18
  • 128
  • 201
Paul Kernaghan
  • 203
  • 1
  • 2
  • 5
  • 1
    Read here for details: http://docs.python.org/tutorial/datastructures.html#dictionaries and note if you new to python - tutorial is you the best friend – Artsiom Rudzenka Jul 05 '11 at 20:03
  • 3
    For testing simple things like this, just use the interactive mode of python. You can experiment and find what is allowed and what is not. – tkerwin Jul 05 '11 at 20:30
  • @Paul Kernaghan: When you tried it, what did you observe? – S.Lott Jul 05 '11 at 21:37

3 Answers3

43

Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple).

You need to use [], not {} to create a list:

{ keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] }
Wooble
  • 87,717
  • 12
  • 108
  • 131
8

Yes, it's possible:

d = {}
d["list key"] = [1,2,3]
print d

output:

{'list key': [1, 2, 3]}
jamylak
  • 128,818
  • 30
  • 231
  • 230
GreenMatt
  • 18,244
  • 7
  • 53
  • 79
0

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

cobie
  • 7,023
  • 11
  • 38
  • 60