Why list indices must be integers, not tuple?
Solution 1
If you're getting that error, then you are trying to index a list, and not a dictionary.
A Python list, like [1, 2, 3]
, must be indexed with integer values. A dictionary, which is what you have in your example, can be indexed by a wider range of different values.
Solution 2
Note that x={}
defines x
to be a dictionary, not a list (which can have any hashable as a key, and with syntactic sugar that translates d[key1,key2]
to d[(key1,key2)]
).
See, however, numpy, which allows multidimensional arrays if that's really what you want.
Solution 3
x = {}
This creates a dictionary, not a list.
x[1,2] = 3
assigns the value 3 to the key (1, 2) a tuple.
A list can only be indexed by integers. Maybe you have mixed up the [] und {} using your dict?
Roman
Updated on March 26, 2020Comments
-
Roman about 4 years
I have this simple program:
x = {} x[1,2] = 3 print x print x[1,2]
It works fine. The fist
print
generates{(1,2):3}
and the second one generates3
.But in my "big" program I seems to do the same but get a
list indices must be integers, not tuple
error. What this error message can mean and how I can resolve this problem?