Why should the list of indices be an integer and not a tuple?

I have this simple program:

x = {} x[1,2] = 3 print x print x[1,2] 

It works great. The fist print generates {(1,2):3} , and the second generates 3 .

But in my "big" program, I seem to be doing the same thing, but I get the error list indices must be integers, not tuple . What can this error message mean and how can I solve this problem?

+4
source share
3 answers

If you get this error, you are trying to index the list, not the dictionary.

A Python list, such as [1, 2, 3] , must be indexed with integer values. The dictionary that you have in your example can be indexed with a wider range of different values.

+12
source

Note that x={} defines x as a dictionary, not a list (which can have any hashed as a key and with syntactic sugar that translates d[key1,key2] to d[(key1,key2)] ).

See, however, numpy , which allows multidimensional arrays if this is really what you want.

+6
source
 x = {} 

This creates a dictionary, not a list.

 x[1,2] = 3 

assigns the value 3 to the key (1, 2) of the tuple.

A list can only be indexed with integers. Maybe you messed up [] und {} using your dict?

+2
source

Source: https://habr.com/ru/post/1336810/


All Articles