与字典相关,我想动态访问超市信息,如果我访问 按照顺序,所有的东西都完美地打印出来,但如果我想随机访问像我想 store1中的access soap是否存在,然后打印“项目不存在”的其他部分
#dictionary to access data
supermarket={'store1':{'name':'vik general store','items':[{'name':'park avenue',
'quantity':200},{'name':'nivea','quantity':100}, {'name':'soap','quantity':500}]}
,'store2':{'name':'lucky general store','items':[{'name':'salt','quantity':600},
{'name':'sugar','quantity':700},{'name':'oil', 'quantity':400}]}}
##taking user input to enter store
s=input('enter the store name:')
#if store 1 opted and then get data from supermarket
if s=='store1':
##every key in item will be considered in sequence
for key in supermarket['store1']['items']:
n=input('enter the product to find:')
if key['name']==n:
print('product detail is :',key['name'],'....',key['quantity'])
else:
print('item is not there')
#if store 2 opted and then get data from supermarket
elif s=='store2':
#every key in item will be considered in sequence
for key in supermarket['store2']['items']:
n=input('enter the product to find:')
if key['name']==n:
print('product detail is :',key['name'],'....',key['quantity'])
else:
print('item is not there')
Op想要随机访问而不是顺序访问,所以我用一个字典替换了Op代码中名为items的数组,其中key作为产品名称,value作为数量
然后在嵌套的if语句中,我使用特殊的
__contains__()
方法检查产品是否存在,该方法返回表示产品存在的bool
,并打印结果相关问题 更多 >
编程相关推荐