When using a dictionary in Python, the following is impossible:
d = {}
d[[1,2,3]] = 4
since \'list\' is an unhashable type
. Ho
The reason is right here (Why must dictionary keys be immutable)
Some unacceptable solutions that have been proposed:
Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:
mydict = {[1, 2]: '12'}
print mydict[[1, 2]]
would raise a
KeyError
exception because the id of the[1, 2]
used in the second line differs from that in the first line. In other words, dictionary keys should be compared using==
, not usingis
.