如何在迭代期间正确更改字典?

时间:2014-05-28 02:34:28

标签: python dictionary

我知道有很多类似的话题,但我的问题却大相径庭。

我有一个非常可怕的程序:

def watchForPositionalMouseRequests(self):

    slotToBeErased = None

    for e in event.get():
        if e.type == MOUSEBUTTONDOWN and mouse.get_pressed()[0] == True:
            if self.isItemSelected == False:
                for slot in self.storage:
                    if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                        print self.storage[slot]
                        if isinstance(self.storage[slot][0],Item):
                            self.isItemSelected = True
                            if self.slotHolder is None:
                                self.storage[slot][0].x = self.cursor.x
                                self.storage[slot][0].y = self.cursor.y
                                self.slotHolder = self.storage[slot][0]
                                slotToBeErased = slot # Here I save the slot to be erased when the mouse is still pressed.

        if e.type == MOUSEBUTTONUP and mouse.get_pressed()[0] == False:
            if self.isItemSelected == True:
                for slot in self.storage:
                    if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                        if self.slotHolder is not None:
                            self.isItemSelected = False
                            self.storage[slot][0] = self.slotHolder
                            self.slotHolder = None
                            self.storage[slotToBeErased] = 0 # Here I remove that saved slot only when I release the mouse button.
                            slotToBeErased = None

结果:

for slot in self.storage:
RuntimeError: dictionary changed size during iteration

我试图在循环外部对self.storage进行深度复制,然后对其进行修改以避免错误,但随后整个应用程序以我从未见过的方式崩溃(我得到了)窗口运行时错误)。我也试图增加递归限制:

sys.setrecursionlimit(10000)

1 个答案:

答案 0 :(得分:3)

您不需要对整个dict进行深度复制,只需复制一个键即可。尝试:

for slot in list(self.storage):