You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何获取字典第二个键对应值并与订购数量相乘

字典价格提取与订单金额计算实现方案

核心实现逻辑

你当前使用的菜单字典为二级嵌套结构,外层字典的key对应选项字母,value为仅包含1组菜名:单价键值对的内层字典。要获取单价(即你所说的第二个对应值)和订购数量做乘法,只需要从选中的内层字典中提取出单价数值即可。

具体修改方法

你可以直接在现有代码末尾追加如下计算逻辑:

# 获取选中的菜品字典
selected_dish = menu(option)
# 提取菜名和单价
dish_name = next(iter(selected_dish.keys()))
dish_price = next(iter(selected_dish.values()))
# 计算总金额
total_amount = dish_price * quantity
# 输出订单明细
print(f"你订购的菜品是:{dish_name},单价:{dish_price}元,数量:{quantity}份,总金额为:{total_amount:.2f}元")

完整可运行代码

chowMenu = {'a': {'Fried Chicken': 99.99}, 'b': {'Chao Fan': 60.99}, 'c': {'Siomai': 45.99}, 'd': {'Chop Suey': 30.00}}
print(" ******** Welcome  to Chowpanda!.********")

def menu(userInput):
    return chowMenu.get(userInput,"Oops! it seems that is not on the menu")
print('\n'.join("{}: {}\n-----------------------".format(k, v) for k, v in chowMenu.items()))
option = input('Please choose your order:')

while  option != 'a' and option != 'b' and option != 'c' and option != 'd' :
    print(menu(option))
    option = input('Please choose your order:')
print(menu(option))
quantity = int(input('How many would you like to order?: '))

# 新增金额计算逻辑
selected_dish = menu(option)
dish_name = next(iter(selected_dish.keys()))
dish_price = next(iter(selected_dish.values()))
total_amount = dish_price * quantity
print(f"订单明细:{dish_name} * {quantity} = {total_amount:.2f}元")

其他可选实现方式

如果不想用next(iter())的写法,也可以直接把内层字典转列表后取值,逻辑完全等效:

dish_price = list(selected_dish.values())[0]

内容的提问来源于stack exchange,提问作者Brilliant Help

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:24:07