如何遍历字典并打印(输出)各个值(Python)

时间:2017-12-24 17:00:34

标签: python loops

我有一项任务是接受用户输入以创建物品的购物清单,并最终将这些信息与总计一起输出到收据上。

示例:用户输入以下杂货:{' name&#39 ;:' milk',' number':1,' price&#39 ;:2.00},{'名称':'鸡蛋','数字':2,'价格':3.99},{&# 39;姓名':'洋葱','号码':4,'价格':0.79}

然后我希望我的输出是:

  

1牛奶@ 2.99美元ea $ 2.99
      2个鸡蛋@ $ 3.99 ea $ 7.98
      4个洋葱@ $ 0.79 ea $ 3.16
      总计:14.13美元

INSTEAD,我的输出是:

  

4个洋葱@ $ 0.79 ea $ 3.16
  4个洋葱@ $ 0.79 ea $ 3.16
  4个洋葱@ $ 0.79 ea $ 3.16
  总计:9.48美元

这是我正在使用的代码。我有一种强烈的感觉,我的循环是责备(他们是我最难掌握的东西),但我不确定为什么它只是一遍又一遍地打印最后一个条目。

grocery_item = {}

grocery_history = []

stop = 'go'

while stop != 'q' :
    item_name = input("Item name:\n")
    quantity = input("Quantity purchased:\n")
    cost = input("Price per item:\n")

    grocery_item['name'] = item_name
    grocery_item['number'] = int(quantity)
    grocery_item['price'] = float(cost)

    grocery_history.append(grocery_item)

print("Would you like to enter another item?")
stop = input("Type 'c' for continue or 'q' to quit:\n")

grand_total = []  

for grocery_item in grocery_history:

    item_total = grocery_item['number'] * grocery_item['price']  
    grand_total.append(item_total)  
    print(grocery_item['number'], end=' ')  
    print(grocery_item['name'],end=' ')  
    print('@', end=' ')  
    print('$%.2f' % (grocery_item['price']), end=' ')  
    print('ea', end=' ')  
    print('$%.2f' % (item_total))  
    item_total = 0  

sum = sum(grand_total)
print('Grand total: $%.2f' % (sum))

4 个答案:

答案 0 :(得分:0)

您可以使用字符串格式:

s = [{'name':'milk', 'number': 1, 'price': 2.00}, {'name':'eggs', 'number':2, 'price': 3.99}, {'name': 'onions', 'number': 4, 'price':0.79}]
for val in s:
   print("{number} {name} @ ${price} ea ${final}".format(**{**val, **{'final':val['number']*val['price']}}))
print('Grand Total: $'+str(sum(val['price']*val['number'] for val in s)))

输出:

1 milk @ $2.0 ea $2.0
2 eggs @ $3.99 ea $7.98
4 onions @ $0.79 ea $3.16
Grand Total: $13.14

编辑:关于为grocery_item初始化添加的代码,grocery_item始终在每次迭代时更新。相反,在while循环的范围内声明grocery_item

while stop != 'q':
   grocery_item = {}

答案 1 :(得分:0)

你的代码工作正常,我在我的电脑上测试过。检查此代码

grocery_history = [{'name':'milk', 'number': 1, 'price': 2.00}, {'name':'eggs', 'number':2, 'price': 3.99}, {'name': 'onions', 'number': 4, 'price':0.79}]
grand_total = []

for grocery_item in grocery_history:

    item_total = grocery_item['number'] * grocery_item['price']
    grand_total.append(item_total)
    print(grocery_item['number'], end=' ')
    print(grocery_item['name'],end=' ')
    print('@', end=' ')
    print('$%.2f' % (grocery_item['price']), end=' ')
    print('ea', end=' ')
    print('$%.2f' % (item_total))
    item_total = 0

sum = sum(grand_total)
print('Grand total: $%.2f' % (sum))

结果如下:

"C:\Programs\Python\Python35\python.exe" F:/MyJobs/StackOverflow/StackOverflow.py
1 milk @ $2.00 ea $2.00
2 eggs @ $3.99 ea $7.98
4 onions @ $0.79 ea $3.16
Grand total: $13.14

Process finished with exit code 0

你应该检查方式,如何" grocery_history"已分配。

答案 2 :(得分:0)

我得到了这段代码希望它有所帮助:[Python3.6]

items = [{'name':'milk', 'number': 1, 'price': 2.00}, {'name':'eggs', 'number':2, 'price': 3.99}, {'name': 'onions', 'number': 4, 'price':0.79}]
grand_total = 0.0
for item in items:
    item_total = item['price'] * item['number']
    grand_total += item_total
    print('{number} {name} @ ${price} ea $'.format(**item) + '{0}'.format(item_total))
print('Grand total: ${0}'.format(grand_total))

答案 3 :(得分:0)

您的grocery_history具有3个元素,所有这3个元素都引用相同的grocery_item

您一直在重复使用与grocery_item相同的dict实例,并将相同的实例多次放入grocery_history

一个快速解决方案是

while stop != 'q' :
    item_name = input("Item name:\n")
    quantity = input("Quantity purchased:\n")
    cost = input("Price per item:\n")

    grocery_item = {}   # a new dict
    grocery_item['name'] = item_name
    grocery_item['number'] = int(quantity)
    grocery_item['price'] = float(cost)
    # or simply do 
    # grocery_item = { "name" : item_name, "number": int(quantity)... }

    grocery_history.append(grocery_item)