繁体   English   中英

Python 访问特定字典元素

[英]Python Accessing Specific Dictionary element

我想从字典中访问用户所需的相应数据索引。当用户提供订单号时。 2然后字典索引2的数据是项目的兴趣..我总是从for循环中获取索引1...

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("Order yor food : ")
     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 is ", total)
             c = input("Do you want to order next? 'n for NO else 'YES' otherwise")
             for key in menuList:
                 print(str(menuList[key]["id"]) + "\t" + menuList[key]["name"]  + "\t" +  str(menuList[key]["price"]))
             break
         else:
             print("Food not available!")
             for key in menuList:
                 print(str(menuList[key]["id"]) + "\t"+ menuList[key]["name"]  + "\t" +  str(menuList[key]["price"]))
             c = input("Do you want to order next? 'n for NO else 'YES' otherwise")
             break
 print("\n\nBill :\n")
 i = 1
 if len(orderlist) > 0:
     for item in orderlist:
         print(i)
         i+=1
         print(item["name"], + item["price"])
     print("Total is Rs.", total , "only")
 else:
     print("No any order")



如果第一个键不匹配,您的 for 循环将进入 else 部分,并告诉用户食物不可用。 您可能希望用在menuList中搜索用户输入来替换for循环,例如

key = next((key for key in menuList if str(menuList[key]['id']) == sel), None)
if key is not None:
    print(f'found menu {key}')

或者 - 更好 - 使用id作为menuList的键。 next(...)在括号中返回迭代器的第一个元素,如果没有则返回None ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM