简体   繁体   中英

Python Accessing Specific Dictionary element

I want to access corresponding data index which is desired by user from the Dictionary.. when a user provide a order no. 2 then the data of index 2 of dictionary is interest of item.. I always get index 1 from for loop...

for key in menuList: // here the problem starts

 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")



Your for loop enters the else part if the first key is not matching and tells the user that the food is not available. You might want to replace the for loop with a search of the user's input in your menuList , like

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

or - better - use the id as key of your menuList . next(...) returns the first element of the iterator in brackets or None if there is none...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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