I seem to receive an error every time I try to remove an item from the dictionary. Here's my code:
print(" MY NEW AND IMPROVED GROCERY LIST ")
def grocerylist():
hist_grocery = []
grocery = True
while grocery:
choice = str(input("\n=====================\nWhat would you like to do? \n1 - Add an item\n2 - Remove an item "
"\n3 - Print entire list\n4 - Calculate cost\n5 - Exit program\nChoice: "))
if choice == "1":
print("=====================\nADD AN ITEM\n")
information = input("Give the following information: \nItem name: ")
price = input("Item price: ")
quantity = input("Item quantity: ")
grocery_list = {"Item name": str(information), "price": float(price), "quantity": int(quantity)}
hist_grocery.append(grocery_list)
** elif choice == "2":
print("=====================\nREMOVE AN ITEM\n")
remove_item = str(input("What would you like to remove? \nItem name: ")).format() # format function
grocery_list = [i for i in hist_grocery if str(i).lower() != remove_item]
**
elif choice == "3":
print("=====================\nPRINTING LIST...")
if hist_grocery == []:
print("The grocery list is empty!")
else:
[print(items, end="\t ") for items in grocery_list.values()]
Here's what I inputted: enter image description here
Tried removing the item egg but it became an error.
Here's what the terminal says: enter image description here
I tried creating another for loop but somehow I got confused along the process. What should I change in my code?
CodePudding user response:
Your error isn't with deleting an item it's with printing the items.
Since you didn't choose option 1 first there is no existing object grocery_list. I'm speculating a bit here but I assume the interpreter sees the for-each loop and assumes that it must be a list, which doesn't have a .values()
method so it gives you this error.
I would try declaring an empty dictionary before your first if block.
CodePudding user response:
The error has almost nothing to do with the "delete" option. The error is in the "print" option. If you look in the code for choice 2, you see that grocery_list = [i...]
, which is definitely a list
. As the error clearly states, you cannot use .values()
with a list
, like when you tried to do so in the 3rd option, where [...for items in grocery_list.values()]
.
PS: Please don't post your error as a picture. It makes it easier for all those involved if it's typed out in the actual question.