views:

114

answers:

2

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.

+10  A: 

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
Mike Graham
You mean dictionary keys, not tuple keys, in the first sentence.
Thomas Wouters
Of course. Thanks.
Mike Graham
"try to keep a dict" => "try to keep a dict valid"
doublep
+2  A: 

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}
joaquin
Keys must be *hashable*, not necessarily *immutable*. You can have mutable values that are hashable (although it's rarely useful) and immutable values that are not hashable (for example, tuples that contain unhashable values.)
Thomas Wouters
Thanks for the comment, though was the same thing... could you give an example of mutable and hashable?
joaquin
@joaquin, For an object to be sanely hashable, the answers it gives when you take its hash and do an equality comparison should never change. The actual object may be able to change in other ways. For example, if I had a class `Person` for defining persons, I may be able to use identity comparison for finding if two `Person` objects are equal no matter if I change things about a `Person`, like their age or address. If the mutability doesn't affect the calculation of equality and hash, it does not keep an object from being hashable.
Mike Graham
@Mike, Thanks for the answer, I just wrote the same question as a new SO question.
joaquin