Search code examples
pythonkeyerror

How to resolve "KeyError: 2"


When I run my application in the following block I get 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

I have to mention that at some point in the program I call self.access.clear(). Even though I have added the first two if conditions but I still get the following error:

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

Any suggestions?


Solution

  • You're checking first if self.access contains anything, and then assuming it contains idno. In this case, it didn't, and idno happened to be 2. Nothing in this code snippet populates self.access, so I don't know what you expect of it.