Create a dictionary in python which is indexed by lists [duplicate]

I would like to create a dictionary which is indexed by lists. For instance, my dictionary should look like:

D = {[1,2,3]:1, [2,3]:3}

Anyone know how to do this? If I just type D([1,2,3]) = 1 it returns an error.


Solution 1:

dict keys must be hashable, which lists are not becase they are mutable. You can change a list after you make it. Think of how tricky it would be to try to keep a dict when the data used as keys changes; it doesn't make any sense. Imagine this scenario

>>> foo = [1, 2]
>>> bar = {foo: 3}
>>> foo.append(4)

and you will see why Python does not try to support lists as keys.

The most obvious solution is to use tuples instead of lists as keys.

>>> d = {[1, 2, 3]: 1, [2, 3]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d = {(1, 2, 3): 1, (2, 3): 3}
>>> d
{(2, 3): 3, (1, 2, 3): 1}
>>> d[2, 3]
3

Solution 2:

Dictionary keys can be only hashable objects. If you want the content of a list as a key you can convert the list to a tuple.

>>>d={}
>>>a = tuple((1,2))
>>>a
(1, 2)
>>>d[a] = 3
>>>print d
{(1, 2): 3}

Solution 3:

d = {repr([1,2,3]): 'value'}

{'[1, 2, 3]': 'value'}

As explained by others (see also here), you cannot use a list directly. You can however use its string representation instead if you really want to use your list.