[英]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...
2然后字典索引2的数据是项目的兴趣..我总是从for循环中获取索引1...
for key in menuList: // here the problem starts 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")
Your for loop enters the else part if the first key is not matching and tells the user that the food is not available.如果第一个键不匹配,您的 for 循环将进入 else 部分,并告诉用户食物不可用。 You might want to replace the
for
loop with a search of the user's input in your menuList
, like您可能希望用在
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}')
or - better - use the id
as key of your menuList
.或者 - 更好 - 使用
id
作为menuList
的键。 next(...)
returns the first element of the iterator in brackets or None
if there is none... next(...)
在括号中返回迭代器的第一个元素,如果没有则返回None
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.