简体   繁体   中英

Why list indices must be integers, not tuple?

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 generates 3 .

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?

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM