0

I am trying to make a function that will receive an input from the user and use that input to delete an item from a dict. The input is assumed to be equivalent to a key. With the code below, I am intending that if 2 is input, then the item 2: "item_b" will be deleted.

With what I have written, I receive a key error. Meanwhile, if I replace i in thedict.pop(i) with 2, the code functions as intended. How do I make thedict.pop(i) read i as a variable?

thedict = {
1: "item_a",
2: "item_b",
3: "item_c"
}
while True:
    i = input("input: ")
    thedict.pop(i)
    print(thedict)
macar0n1
  • 3
  • 1

2 Answers2

0

input reads a string. Your keys are integers. So you need to convert the input to an integer, for example with int(i).

rici
  • 234,347
  • 28
  • 237
  • 341
0

input() returns string while your keys are integers. Try the following:

thedict = {
1: "item_a",
2: "item_b",
3: "item_c"
}
while True:
    i = input("input: ")
    // int() converts string to integer, 
    // The additional parameter suppresses error if the key is not present
    thedict.pop(int(i), None)
    print(thedict)
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26