如何为列表中的项获取字典项的值?python

2024-06-16 10:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

menuePrice = { 
"margherita":5.00,#the price is 5.00
"pepperoni": 7.50,
"ham and pinaple": 1,
"vegan pizza": 1,
"americano": 1,
"meat pizza": 1,
"gluten free pizza": 1,
"dary free pizza": 1,
"pizza free pizza": 1,
"p": 1,
}

这是名单 pizzaOrder = ["margherita", "pepperoni"]#this is what the customer has ordered

您好,我想从menuePrice获取pizzaOrder中的任何东西的值,将这些值相加并打印出来作为最终价格。总计:12.5英镑。我没有尝试过任何东西,因为我不知道如何去做,我正在努力将我的问题表达成谷歌的文字。 这是一个比萨饼订单聊天机器人,如果有帮助。很抱歉,如果答案很简单,我/我对python中的字典还很陌生/


Tags: andthefreeispricehampizzameat
2条回答

假设您想要得到总价:

menuePrice = { 
    "margherita":5.00,#the price is 5.00
    "pepperoni": 7.50,
    "ham and pinaple": 1,
    "vegan pizza": 1,
    "americano": 1,
    "meat pizza": 1,
    "gluten free pizza": 1,
    "dary free pizza": 1,
    "pizza free pizza": 1,
    "p": 1,
}

pizzaOrder = ["margherita", "pepperoni"]  #this is what the customer has ordered
total = 0

for pizza in pizzaOrder:
    total += menuePrice[pizza]

print(total)

只需使用for-each循环对字典的值进行迭代(即单词):

total = 0
for price in menuePrice.values():
    total += price

相关问题 更多 >