1

I don't get KeyError when I use a constant (whose value is the same as the variable) for [key].

For example:

self._answer= input("Which appointment would you like to delete?")
self._useless= self._book.pop(self._answer)

Gives a key error when self._answer= 1001, however:

self._useless= self._book.pop(1001)

works as desired. Any ideas how I can resolve this issue?

Edit: As @user2357112 suggested below, the following piece of code worked: def deleteAppointment(self): self._answer= int(input("Which appointment would you like to delete?")) del self._book[self._answer]

However, after redoing the entire project I no longer ran into the problem above (i.e. using [dictionary].pop([key]) no longer produced a KeyError). Therefore, if you are getting this error there is likely a bug in your code.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

1 Answers1

2

input on Python 3 returns a string, and '1001' != 1001. If your key is the int 1001, you will need to convert the input to an int:

self._answer= int(input("Which appointment would you like to delete?"))

As an aside, the name self._useless indicates that you might not care about the result of the pop operation. If you just want to remove the entry from the dict, you can use del:

del self._book[self._answer]

or you could ignore the return value of pop and not assign it to anything:

self._book.pop(self._answer)
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks you user2357112, your second suggestion using del worked. As a side note, your first suggestion didn't work for me: when I tried it there were no errors, however 1001 was still in the dictionary. –  Apr 06 '16 at 23:59
  • @AshutoshMishra: Sounds like you've got more bugs somewhere. – user2357112 Apr 06 '16 at 23:59