如何提取键及其值并添加值以在 python 字典中打印总数?

How to extract keys with its values and add values to print the total in python dictionary?

我这里有一家餐厅的菜单及其价格。我想检查订单并添加价格并打印订单总价。但我无法提取特定订单的键值。如何像

一样一起显示订单及其价格

马来苏达:14.00 美元
抱歉,我们没有披萨
梅塞纳斯:12.00 美元

总价:26.00 美元

menu_items = {
    'nulla aliquam': 15.00,
    'malesuada': 14.00,
    'feugiat ipsum': 9.00,
    'maecenas': 12.00,
    'fermentum mass': 23.00
}
ordered_items = {
    'maecenas',
    'pizza',
    'malesuada'
}
for item in ordered_items:
    if item in menu_items.keys():
      print(item)
    else:
      print("sorry we dont have ",item)

您可以使用列表理解来获取 ordered_items 中项目的菜单价格,请注意您为 ordered_items 创建的结构是 set 而不是字典.

menu_items = {
    'nulla aliquam': 15.00,
    'malesuada': 14.00,
    'feugiat ipsum': 9.00,
    'maecenas': 12.00,
    'fermentum mass': 23.00
}
ordered_items = {
    'maecenas',
    'pizza',
    'malesuada'
}

totalPrice = sum([v for k,v in menu_items.items() if k in ordered_items])
print(totalPrice)

输出:

26.0

列表理解只是执行以下 for 循环的一种更好的方式:

编辑 为您指定订单中每个项目的打印。

total_price = 0 
for item in ordered_items:
    if item in menu_items:
        print(f"{item} : ${menu_items[item]} ")
        total_price += menu_items[item]
    else:
        print(f"Sorry, we don't have {item}")
print(f'Total : ${total_price}')

输出:

梅塞纳斯:12.0 美元

抱歉,我们没有披萨

马来苏达:14.0 美元

总计:26.0 美元

要在一行上打印所有这些,请在每个循环中将每个语句附加到一个字符串并在最后打印:

total_price = 0 
printString = ''
for item in ordered_items:
    if item in menu_items:
        printString += f"{item} : ${menu_items[item]} "
#        print(f"{item} : ${menu_items[item]} ")
        total_price += menu_items[item]
    else:
#        print(f"Sorry, we don't have {item}")
        printString += f"Sorry, we don't have {item} "
#print(f'Total : ${total_price}')
printString +=  f"Total : ${total_price} "

print(printString)

输出:

maecenas:$12.0 抱歉,我们没有 pizza malesuada:$14.0 总计:$26.0

两件事:

  • 您不需要使用 .keys() 来检查字典中是否存在关键字

  • 您使用字典索引访问价格:dictionary[key] -> value

total = 0
for item in ordered_items:
    if item in menu_items:
        print('{} : ${:2f}'.format(item, menu_items[item]))
        total += menu_items[item]
    else:
        print('Sorry we don\'t have {}'.format(item))

print('Total price : ${:2f}'.format(total))