Python 类型错误:索引到字典时“类型”对象不可下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26920955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:10:01  来源:igfitidea点击:

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

pythonpython-3.xdictionary

提问by Chanヨネ

I have multiple files that I need to load so I'm using a dictto shorten things. When I run I get a

我有多个文件需要加载,所以我使用 adict来缩短内容。当我跑步时,我得到一个

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))

采纳答案by b4hand

Normally Python throws NameErrorif the variable is not defined:

通常,NameError如果未定义变量,Python 会抛出:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

但是,您已经设法偶然发现了 Python 中已经存在的名称。

Because dictis the name of a built-in type in Pythonyou are seeing what appears to be a strange error message, but in reality it is not.

因为dict是 Python 中内置类型的名称,所以您看到的似乎是一条奇怪的错误消息,但实际上并非如此。

The type of dictis a type. All types are objects in Python. Thus you are actually trying to index into the typeobject. This is why the error message says that the "'type' object is not subscriptable."

的类型dicttype。所有类型都是 Python 中的对象。因此,您实际上是在尝试对type对象进行索引。这就是错误消息指出“'type' 对象不可下标”的原因。

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dictname, but you really don't want to do that.It's just going to cause you problems later.

请注意,您可以盲目地分配dict名称,但您确实不想这样做。以后只会给你带来麻烦。

>>> 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))