首页 > 解决方案 > 尝试从字典中打印时出现关键错误

问题描述

当我运行以下代码时,我收到一个键错误“名称”。我相信我的字典中的名字是被定义的,所以我不确定错误的来源是什么。

''' 任务分为三个部分。

任务:创建空数据结构

grocery_item = {}

grocery_history = []

用于检查 while 循环条件是否满足的变量

stop = False

虽然不停:

#接受购买的杂货商品名称的输入。

name = input("item Name:\n")

#接受购买的杂货数量的输入。

quantity = input("quantity purchased:\n")

#接受杂货商品输入成本的输入(这是每件商品的成本)。

cost = input("price per item:\n")

#使用更新函数创建一个字典条目,其中包含用户输入的名称、数字和价格。

grocery_item = {'item_name':(name), 'quantity':int(quantity), 'cost':float(cost)}

#使用append函数将grocery_item添加到grocery_history列表中

grocery_history.append(grocery_item)

#接受来自用户询问他们是否已经完成输入杂货的输入。

  response = input("Would you like to enter another item?\n Type 'c' to continue or 'q' to quit:\n")
  if response == 'q':
    stop = True

定义变量以保存名为“grand_total”的总计

grand_total = 0

定义一个“for”循环。

for item in grocery_history:

#计算grocery_item的总成本。

item_total = item['quantity'] * item['cost']

#将 item_total 添加到 grand_total

grand_total += item_total

#输出杂货项目的信息以匹配这个例子:#2 apple @ $1.49 ea $2.98

print("{} {} @ ${} ea {}" .format(item['quantity'], item['name'], item['cost'], item_total))

#设置item_total等于0

item_total = 0

打印总计

print ("Grand Total: $"(grand_total))

Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?

标签: keyerror

解决方案


name应该是item_name,因为这一行:

grocery_item = {'item_name':(name), 'quantity':int(quantity), 'cost':float(cost)}

您将输入分配nameitem_name.

因此,这一行:

print("{} {} @ ${} ea {}" .format(item['quantity'], item['name'], item['cost'], item_total))

应替换为:

print("{} {} @ ${} ea {}" .format(item['quantity'], item['item_name'], item['cost'], item_total))


推荐阅读