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.
解决方案
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 "", line 1, in
TypeError: unhashable type: 'list'
>>> d = {(1, 2, 3): 1, (2, 3): 3}
>>> d
{(2, 3): 3, (1, 2, 3): 1}
>>> d[2, 3]
3