keyerror - 尝试从字典中打印时出现关键错误
问题描述
当我运行以下代码时,我收到一个键错误“名称”。我相信我的字典中的名字是被定义的,所以我不确定错误的来源是什么。
''' 任务分为三个部分。
- 第 1 部分 - 用户输入
- 第 2 部分 - 遍历购物清单
- 第 3 节 - 向控制台提供输出 '''
任务:创建空数据结构
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?
解决方案
name
应该是item_name
,因为这一行:
grocery_item = {'item_name':(name), 'quantity':int(quantity), 'cost':float(cost)}
您将输入分配name
给item_name
.
因此,这一行:
print("{} {} @ ${} ea {}" .format(item['quantity'], item['name'], item['cost'], item_total))
应替换为:
print("{} {} @ ${} ea {}" .format(item['quantity'], item['item_name'], item['cost'], item_total))
推荐阅读
- android - 从服务启动活动后,应用程序再次从后台打开
- npm - Webpack 生产构建不生成构建输出并且几乎没有终端日志消息
- node.js - 在 Azure 中配置节点应用程序
- c++ - What are the functions that look like table in Lua?
- html - 我的导航栏“位置粘滞”已停止工作,我不知道为什么
- verilog - always_comb 中的临时变量会创建锁存器吗
- pip - DAL-script 在 github 和 pip install 之间是不同的
- angular - Creating an Interface of a data consist of object and array of objects
- javascript - `"\n"` can't run in `new Function()`
- java - Does threads of ThreadPoolExecutor not runs concurrently using with PriorityBlockingQueue