【发布时间】:2018-05-08 22:07:58
【问题描述】:
我正在为班级制作一份简单的购物清单。第一步,我们创建一个空字典和列表,由用户输入填充。所有杂货项目都进入字典 (grocery_item{}),所有字典都将添加到列表 (grocery_history)。
我的脚本目前如下所示:
grocery_item = {}
grocery_history = []
stop = 'go'
while stop == 'go' or stop == 'c':
item_name = input("Item name: \n" )
quantitiy = int(input("Quantitiy purchased:\n" ))
cost = float(input("Price per item:\n" ))
grocery_item.update({'name' : item_name, 'number' : quantitiy, 'price' :
cost})
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\n Type 'c' for continue
or 'q' to quite:\n")
如果我此时打印grocery_history,它将完全按照我的意图打印字典列表。在购物清单的下一步中,我们试图找到物品的总数。但是,每当我尝试查找每个项目的单独值时,使用 for 循环来获取列表中的每个字典,我都会收到一个错误,声称未定义键,即使它只是打印了该杂货项目的字典条目,并且所有的键有值。
本节的脚本如下所示:
grand_total = 0
for item in grocery_history:
I = 0
for price in item:
item_total = number * price
grand_total += item_total
print(number + name + '@' + '$' + price + 'ea' + '$' + round(item_total,2))
item_total = 0
I += 1
print('$' + round(grand_total,2))
错误是针对我尝试查找 item_total 的行,因为这是我尝试使用其中一个键的第一行。我尝试将密钥重写为grocery_item(numbers)/grocery_item(price),并收到相同的错误消息。
感谢您的帮助,提前致谢!
【问题讨论】:
-
这不是 Python 字典的工作方式。
-
嗨!在您的第二部分中,每个
item都是一本字典(杂货),不是吗?如果是这样,那么您不需要第二个for循环;您可以通过item['price']访问商品的价格。 -
不要遍历
item,直接访问你需要的item['price']或item['name']例如。
标签: python python-3.x dictionary key-value