【问题标题】:I am getting a key error when trying to print from my dictionary尝试从字典中打印时出现关键错误
【发布时间】:2019-07-27 17:04:35
【问题描述】:

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

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

  • 第 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 苹果 @ $1.49 一个 $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?

【问题讨论】:

  • 最好用它所写的语言标记您的帖子。因此,例如,如果这是用 python 编写的,则将其标记为 python 以及 keyerror。这样,查看 python 帖子的人也会看到您的帖子。

标签: keyerror


【解决方案1】:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多