【问题标题】:Dictionary value "not defined" Python字典值“未定义”Python
【发布时间】: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


【解决方案1】:

试试这样的:

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 循环,你需要遍历字典的键。您可以通过使用字典的.keys().items() 函数来做到这一点。但正如您在上面看到的,没有必要在代码中循环遍历 dict 键。

【讨论】:

    【解决方案2】:
    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.")
    

    【讨论】:

    • 上面缺少的是第 21 行的 str() 方法。我还重新格式化了几行,你将 "$" 与 "@" 连接起来,以便为审美目的留出一些空间。我希望这就是你要找的......
    • 您可以使用编辑按钮编辑您自己的答案。这比在您的答案中添加评论要好。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2012-08-15
    • 2022-11-14
    相关资源
    最近更新 更多