Create a dictionary in python that is indexed by lists

I would like to create a dictionary that is indexed by lists. For example, my dictionary should look like this:

D = {[1,2,3]:1, [2,3]:3} 

Does anyone know how to do this? If I just type D([1,2,3]) = 1 , it returns an error.

+7
python dictionary
Apr 19 '10 at 21:59
source share
3 answers
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 
+17
Apr 19 '10 at 10:10
source share

Dictionary keys can only be hashed objects. If you want the contents of the list as a key, you can convert the list into a tuple.

 >>>d={} >>>a = tuple((1,2)) >>>a (1, 2) >>>d[a] = 3 >>>print d {(1, 2): 3} 
+2
Apr 19 '10 at 22:11
source share
 d = {repr([1,2,3]): 'value'} {'[1, 2, 3]': 'value'} 

As explained by others (see also here) , you cannot use the list directly. However, you can use its string representation if you really want to use your list.

+1
Aug 31 '11 at 14:00
source share



All Articles