从字典中删除项目"grocery_list"会导致错误



每次尝试从字典中删除条目时,我似乎都会收到一个错误。下面是我的代码:

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 itemn2 - Remove an item "
"n3 - Print entire listn4 - Calculate costn5 - Exit programnChoice: "))
if choice == "1":
print("=====================nADD AN ITEMn")
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 ITEMn")
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()]

我输入的是:输入图像描述

尝试移除物品蛋,但出现错误。

终端显示如下:输入图片描述

我尝试创建另一个for循环,但不知何故,我在这个过程中感到困惑。我应该在代码中修改什么?

您的错误不是删除项目,而是打印项目。

由于您没有首先选择选项1,因此没有存在的对象grocery_list。我在这里做了一些推测,但我假设解释器看到了for-each循环,并假设它必须是一个列表,它没有.values()方法,所以它给了你这个错误。

我会尝试在第一个if块之前声明一个空字典。

这个错误几乎与"delete"选择。错误在"打印"中。选择。如果你看一下选项2的代码,你会看到grocery_list = [i...],它肯定是一个list。正如错误明确指出的那样,您不能将.values()list一起使用,就像您在第三个选项中尝试这样做一样,其中[...for items in grocery_list.values()].

PS:请不要把你的错误贴在图片上。如果在实际问题中打印出来,对所有相关人员来说都更容易。

最新更新