Python 如何解决;关键错误:2“;

Python 如何解决;关键错误:2“;,python,keyerror,Python,Keyerror,当我在以下程序块中运行应用程序时,我得到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

当我在以下程序块中运行应用程序时,我得到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,因此我不知道您对它的期望

谢谢@yann vernier,我想我现在理解了这个问题。
如果bool(…)
是多余的。如果改为…,则应为