字典类型错误:列表索引必须是整数或切片,而不是 str

时间:2021-02-07 11:12:35

标签: python python-3.x dictionary

我有一个简单的程序:

import pygame

textures = {"on_start.png":"(pygame image)","print.png":"(pygame image)"}

class block(pygame.sprite.Sprite):
    def __init__(self,initx,inity,initp,initty,initte,initid):
        super().__init__()
        self.xpos = initx
        self.ypos = inity
        self.parent = initp
        self.blockType = initty
        self.texture = textures[initte]
        self.blockID = initid
        block_loop.add(self)

def load():
    global block_loop, block_store, blockNumber
    block_store = []
    block_loop = pygame.sprite.Group()
    pend1 = {"next":2,"0":{"type":"on_start","x":50,"y":50,"parent":-1},"1":{"type":"print","x":0,"y":0,"parent":0}}
    blockNumber = pend1["next"]
    del pend1["next"]
    for item in pend1:
        #print(pend1[item]["x"],pend1[item]["y"],pend1[item]["parent"],pend1[item]["type"],pend1[item]["type"] + ".png",item)
        block_store[item] = block(pend1[item]["x"],pend1[item]["y"],pend1[item]["parent"],pend1[item]["type"],pend1[item]["type"] + ".png",item)

load()

当我运行它时出现此错误:

pygame 2.0.1 (SDL 2.0.14, Python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\*PATH*\program.py", line 27, in <module>
    load()
  File "C:\Users\*PATH*\program.py", line 25, in load
    block_store[item] = block(pend1[item]["x"],pend1[item]["y"],pend1[item]["parent"],pend1[item]["type"],pend1[item]["type"] + ".png",item)
TypeError: list indices must be integers or slices, not str

我已经对值进行了打印()处理(请参阅第 24 行中的注释)并且它们都被正确打印,所以我不知道为什么会出现此错误。我已经尝试将代码弄乱了大约一个小时,但仍然收到此错误,即使这不是列表而是字典,并且我可以通过与定义精灵相同的方法使用 print() 函数成功访问这些值。这是一个非常令人困惑的问题,任何帮助将不胜感激。

注意:我没有包含 pygame 标签,因为我认为它与问题无关。

问题版本 #2

1 个答案:

答案 0 :(得分:0)

当你迭代一个字典时,pend1 你迭代键。在您的情况下,删除键 next 后,item 将取值 "0""1"。这些是 str 并且正如错误所说,列表索引需要是整数。即使这些是 int 项目分配也不起作用,因为列表开始是空的。因为要使用值,所以最好迭代 pend1.items():

for key, value in pend1.items():
    block_store.append(block(value["x"], value["y"], value["parent"], value["type"], f'{value["type"]}.png', key))

这将用 2 个块类型的元素填充 block_store(顺便说一下,类名应该是 TitleCase,例如 Block)。迭代 dict 项目的顺序也取决于 python 版本。 3.7 之前的 dicts 不保留插入顺序。