Keys
dict must be hashed, and lists should not be because they are mutable. You can change the list after creating it. Think about how difficult it would be to try to save a dict when the data used as keys changes; it makes no sense. Imagine this scenario
>>> foo = [1, 2] >>> bar = {foo: 3} >>> foo.append(4)
and you will understand why Python is not trying to maintain 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 Apr 19 '10 at 10:10 2010-04-19 22:10
source share