How to resolve "KeyError: 2"

How to resolve "KeyError: 2"

当我 运行 我在以下块中的应用程序时,我得到 KeyError 2:

if bool(self.access):  # to check if it is empty or not
    if no in self.access[idno]:
        if (idno, no) in self.table:
            if self.table[(idno, no)] == (idx, macx):
                return
            else:
                self.table[(idno, no)] = (idx, macx)
                return
        else:
            self.table.setdefault((idno, no), set())
            self.table[(idno, no)] = (idx, macx)
            return

我不得不提到,在我调用 self.access.clear() 的程序中的某个时刻。 即使我已经添加了前两个 if 条件,但我仍然收到以下错误:

line 189, in register_idx
    if no in self.access[dpid]:
KeyError: 2

有什么建议吗?

您首先检查 self.access 是否包含 任何内容,然后假设它包含 idno。在这种情况下,它没有,idno 恰好是 2。此代码片段中没有任何内容填充 self.access,所以我不知道您对它的期望是什么。