hugfyf45553
hugfyf45553

Reputation: 25

How do I delete an Input from a Dictionary?

My code:

print("Please enter your favourite foods")
a = input("Food 1: ")
b = input("Food 2: ")
c = input("Food 3: ")
d = input("Food 4: ")

food = {1:a, 2:b, 3:c, 4:d}
print(food)

Q = input("Which food would you like to remove?: ")

food.pop(Q)
sorted(food)

print(food)

I want the user to remove one item from the dictionary but every time they input what they want to remove I keep getting the error:

KeyError: 'whatever the user inputted'

(P.S I'm not allowed to make it into a list)

Upvotes: 0

Views: 55

Answers (1)

Seth
Seth

Reputation: 2370

You should convert the user input into an int, because the dictionary keys are ints. Here's an example implementation:

print("Please enter your favourite foods")
a = input("Food 1: ")
b = input("Food 2: ")
c = input("Food 3: ")
d = input("Food 4: ")

food = {1:a, 2:b, 3:c, 4:d}
print(food)

Q = int(input("Which food would you like to remove?: "))

food.pop(Q)
sorted(food)

print(food)

Upvotes: 2

Related Questions