Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 568
Chris Avatar asked Apr 19 '10 21:04

Chris


1 Answers

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
like image 193
Mike Graham Avatar answered Oct 17 '22 04:10

Mike Graham