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'
(PS I'm not allowed to make it into a list)
You should convert the user input into an int
, because the dictionary keys are int
s. 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.