动态字典访问

2024-06-02 08:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

与字典相关,我想动态访问超市信息,如果我访问 按照顺序,所有的东西都完美地打印出来,但如果我想随机访问像我想 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')
    

Tags: tostorekeynameininputifitems
1条回答
网友
1楼 · 发布于 2024-06-02 08:15:13

Op想要随机访问而不是顺序访问,所以我用一个字典替换了Op代码中名为items的数组,其中key作为产品名称,value作为数量

然后在嵌套的if语句中,我使用特殊的__contains__()方法检查产品是否存在,该方法返回表示产品存在的bool,并打印结果

#dictionary to access data
supermarket = {
                'store1': { 
                            'name':'vik general store',
                            'items': { 'park avenue':200, 'nivea':100, 'soap':500 }
                        },
                'store2': {
                            'name':'lucky general store',
                            'items':{ 'salt':600, 'sugar':700, 'oil':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':
    n=input('enter the product to find:')
    if supermarket['store1']['items'].__contains__(n):
        print('product detail is :',n,'....',supermarket['store1']['items'][n])
    else:
        print('item is not there')

#if store 2 opted and then get data from supermarket
elif s=='store2':
    n=input('enter the product to find:')
    if supermarket['store2']['items'].__contains__(n):
        print('product detail is :',n,'....',supermarket['store1']['items'][n])
    else:
        print('item is not there')

相关问题 更多 >