字典值“未定义”Python

g9icjywg  于 2023-02-17  发布在  Python
关注(0)|答案(2)|浏览(148)

我正在为课堂编写一个简单的杂货清单。在第一步中,我们创建一个空的字典和清单,由用户输入来填充。所有的杂货项目都进入一个字典(mergery_item{}),所有的字典都被添加到清单(mergery_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")

如果我在这里打印growth_history,它将完全按照我的意图打印字典列表。在growth列表的下一步中,我们将试图找到项目的总计。然而,每当我试图找到每个项目的单独值时,使用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的那一行,因为这是我尝试使用其中一个键的第一行。我曾尝试将键重写为groush_item(numbers)/groush_item(price),但收到了相同的错误消息。
我感谢任何帮助,并提前感谢!

plicqrtu

plicqrtu1#

试试这样的方法:

grocery_history = [] 
stop = 'go' 
while stop == 'go' or stop == 'c':
    grocery_item = {}
    grocery_item['name'] = input("Item name: \n" )  
    grocery_item['number'] = int(input("Quantitiy purchased:\n" )) 
    grocery_item['price'] = float(input("Price per item:\n" ))     
    grocery_history.append(grocery_item) 
    stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quit:\n")

grand_total = 0 
for item in grocery_history: 
    item_total = 0 
    item_total = item['number'] * item['price']  
    grand_total += item_total  
    print(item['number'], item['name'], '@', '$', item['price'], 'ea', '$', round(item_total,2))
print('$', round(grand_total,2))

如果你想在字典上使用for循环,你需要循环字典的键,你可以通过使用dict的.keys().items()函数来实现,但是如上所述,你的代码中不需要循环dict键。

juzqafwq

juzqafwq2#

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 quit:\n")

grand_total = 0
for item in grocery_history:
    item_total = item['number'] * item['price']
    grand_total += float(item_total)
    print(str(item['number']) + " " +  str(item['name']) + ' @ ' + '$' + str(item['price']) + 'ea' + "\n" + '$'  + str(round(item_total,2)))
    item_total = 0
print("\n" + '$' + str(round(grand_total,2)) + " is the grand total.")

相关问题