TypeError:索引到字典时,'type'对象不可下标 [英] TypeError: 'type' object is not subscriptable when indexing in to a dictionary
问题描述
我有多个文件需要加载,所以我使用一个 dict
来缩短事情。当我运行我得到一个TypeError:类型'对象不可下标'错误。如何获得这个工作?
I have multiple files that I need to load so I'm using a dict
to shorten things. When I run I get a "TypeError: 'type' object is not subscriptable" Error. How can I get this to work?
m1 = pygame.image.load(dict[1])
m2 = pygame.image.load(dict[2])
m3 = pygame.image.load(dict[3])
dict = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
playerxy = (375,130)
window.blit(m1, (playerxy))
推荐答案
如果变量未定义,通常Python会抛出 NameError
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
但是,您已经成功绊倒在Python中已经存在的名称。
However, you've managed to stumble upon a name that already exists in Python.
因为 dict
是Python中内置类型的名称,您将看到似乎是一个奇怪的错误消息,但实际上不是。
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
dict的类型
是一个类型
。所有类型都是Python中的对象。因此,您实际上正在尝试索引到类型
对象。这就是为什么错误消息说'type'对象不可下标。
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
请注意,您可以盲目分配给 dict
名称,但您真的不想这样做。稍后会导致您出现问题。
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
问题的真正原因是你必须在尝试使用它们之前分配变量。如果你只是重新排列你的问题的陈述,几乎肯定会奏效:
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
这篇关于TypeError:索引到字典时,'type'对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!