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

Python字典指定元素访问异常:输入订单号2却获取id=1的数据

字典遍历无法匹配指定ID数据的问题

我想从字典中获取用户指定ID对应的菜品数据,当用户输入订单号2时,期望获取ID为2的Pizza条目,但通过for循环遍历字典时,总是只能获取到ID为1的MOMO数据,输入其他ID直接提示不存在。相关代码如下:

# 这里就是问题开始的地方
for key in menuList: 
    menuList={}
    menuList["momo"] = {'id' : 1,'name' : 'MOMO','price':80}
    menuList["pizza"] = {'id' : 2,'name' : 'Pizza','price':180}
    for key in menuList:
        print(str(menuList[key]["id"]) + "\t" + menuList[key]["name"]  + "\t" +  str(menuList[key]["price"]))

    c = 'y'
    orderlist = []
    total = 0
    while(c !='n'):
        sel = input("请输入菜品编号点餐:")
        for key in menuList:
            if sel == str(menuList[key]["id"]):
                print(menuList[key]["name"]  + "\tRs. " +  str(menuList[key]["price"]))
                orderlist.append(menuList[key])
                total = total + menuList[key]["price"]
                print("当前总价:", total)
                c = input("是否继续点餐?输入'n'结束,其他任意键继续:")
                # 重新打印菜单
                for key in menuList:
                    print(str(menuList[key]["id"]) + "\t" + menuList[key]["name"]  + "\t" +  str(menuList[key]["price"]))
                break
            else:
                print("菜品不存在!")
                # 重新打印菜单
                for key in menuList:
                    print(str(menuList[key]["id"]) + "\t"+ menuList[key]["name"]  + "\t" +  str(menuList[key]["price"]))
                c = input("是否继续点餐?输入'n'结束,其他任意键继续:")
                break
    print("\n\n账单:\n")
    i = 1
    if len(orderlist) > 0:
        for item in orderlist:
            print(i)
            i+=1
            print(item["name"], + item["price"])  # 这里有语法错误
        print("总价:Rs.", total , "仅需")
    else:
        print("未下单")

核心问题分析

  1. 多余的外层循环:最顶部的for key in menuList:完全无意义,且循环内部重新赋值menuList,会导致初始遍历逻辑混乱(若menuList未提前定义还会直接报错)。
  2. 遍历中断过早:点餐逻辑里的for循环,只要第一个菜品(ID1的MOMO)不匹配用户输入,就直接进入else分支并break,根本没机会遍历第二个菜品(ID2的Pizza),所以永远无法匹配到ID2的数据。
  3. 语法错误:账单打印处的print(item["name"], + item["price"])多了一个逗号加加号,会触发语法报错。

修复后的代码

# 初始化菜单字典,仅定义一次
menuList={}
menuList["momo"] = {'id' : 1,'name' : 'MOMO','price':80}
menuList["pizza"] = {'id' : 2,'name' : 'Pizza','price':180}

# 打印初始菜品列表
print("菜品列表:")
for key in menuList:
    print(f"{menuList[key]['id']}\t{menuList[key]['name']}\tRs.{menuList[key]['price']}")

c = 'y'
orderlist = []
total = 0
while c != 'n':
    sel = input("\n请输入菜品编号点餐:")
    # 标记是否找到匹配菜品
    found = False
    for key in menuList:
        if sel == str(menuList[key]["id"]):
            found = True
            print(f"{menuList[key]['name']}\tRs.{menuList[key]['price']}")
            orderlist.append(menuList[key])
            total += menuList[key]["price"]
            print(f"当前总价:Rs.{total}")
            break
    # 遍历完所有菜品后再判断是否存在
    if not found:
        print("菜品不存在!")
    
    # 统一询问是否继续点餐
    c = input("是否继续点餐?输入'n'结束,其他任意键继续:")
    # 重新打印菜单
    print("\n菜品列表:")
    for key in menuList:
        print(f"{menuList[key]['id']}\t{menuList[key]['name']}\tRs.{menuList[key]['price']}")

# 打印最终账单
print("\n\n账单:\n")
i = 1
if len(orderlist) > 0:
    for item in orderlist:
        print(f"{i}. {item['name']} Rs.{item['price']}")
        i += 1
    print(f"总价:Rs.{total} 仅需")
else:
    print("未下单")

修复说明

  • 移除了多余的外层循环,将菜单初始化放在代码最开头,避免重复定义。
  • 增加found标记,遍历完所有菜品后再判断是否匹配,避免提前中断遍历流程。
  • 重构了询问继续点餐的逻辑,消除重复代码。
  • 修复账单打印的语法错误,使用f-string简化字符串拼接,提升代码可读性。

内容的提问来源于stack exchange,提问作者Sajan Duwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:39:28