2017-06-02 337 views
0

我有一個小蟒蛇功能的問題,目前我有這樣的結構:如何獲取列表中嵌套字典的值?

dict_conf = {'conf_storage': 
      {'option1':[ 
       {'number':'20169800'}, 
       {'name':'usb'}, 
       {'description':'16gb'}, 
       {'qty':'1'}, 
       {'vendor=':'XLR'}, 
       {'online':'Yes'}], 
      'option2':[ 
       {'number':'20161789'}, 
       {'name':'hardrive'}, 
       {'description':'128gb'}, 
       {'qty':'1'}, 
       {'vendor=':'KBW'}, 
       {'online':'NO'}]}, 
     'conf_grph': 
       {'option1':[ 
        {'number':'20170012'}, 
        {'name':'HD_screen'}, 
        {'description':'1080p'}, 
        {'qty':'1'}, 
        {'vendor=':'PWD'}, 
        {'online':'Yes'}]}} 

conf_type = raw_input("Enter the conf type: ") 
option = raw_input("Enter the option") 

我想找到「數量」值,例如,如果用戶輸入:

conf_type = "conf_storage" 
number = "20169800" 

然後打印該值並顯示一條消息:「您輸入了一個有效的數字,它是:20169800」

我的想法是迭代並返回與用戶輸入的值相同的值。

如果我使用iteritems我得到的每個元素,然後我可以把它放到一個for循環,但之後,我不知道我怎麼能進入列表中包含字典和檢索「數字」鍵的值。

如果你有答案,你能解釋給我,我的意思是你怎麼找到該怎麼做。

感謝

+1

爲什麼你會擁有單一值的詞典列表? '[{'number':'20169800'},{'name':'usb'},...] – AChampion

+0

沒錯。將價值作爲詞典而不是詞典列表會更有意義。 – Barmar

+0

你實際得到'conf_type'&'option'或'conf_type&number'是什麼輸入? – AChampion

回答

1

一個簡單的解決方案可能是隻是遍歷所有元素。

conf_type = "conf_storage" 
number = "20169800" 

if dict_conf[conf_type]: 
    for key, value in dict_conf[conf_type].items(): 
     for v in value: 
      for k,num in v.items(): 
       if num == number: 
        print('found') 
0

這應做到:

print "You entered a valid number, it is:", dict_conf[conf_type][option][0]['number'] 

https://repl.it/I3tr

+0

你從哪裏得到'option'變量? – AChampion

+0

原始輸入...看原始帖子 – kbball

+0

瞭解,OP顯示輸入的內容與代碼中顯示的不一致。 – AChampion

0

改造numbers成一個列表,並檢查進入number在列表例如:

conf_type = "conf_storage" 
number = "20169800" 

if number in [option[0]['number'] for option in dict_conf[conf_type].values()]: 
    print("You entered a valid number, it is: {}".format(number)) 
# You entered a valid number, it is: 20169800 
0

這是完整的工作代碼:

dict_conf = {'conf_storage': 
      {'option1':[ 
       {'number':'20169800'}, 
       {'name':'usb'}, 
       {'description':'16gb'}, 
       {'qty':'1'}, 
       {'vendor=':'XLR'}, 
       {'online':'Yes'}], 
      'option2':[ 
       {'number':'20161789'}, 
       {'name':'hardrive'}, 
       {'description':'128gb'}, 
       {'qty':'1'}, 
       {'vendor=':'KBW'}, 
       {'online':'NO'}]}, 
    'conf_grph': 
      {'option1':[ 
       {'number':'20170012'}, 
       {'name':'HD_screen'}, 
       {'description':'1080p'}, 
       {'qty':'1'}, 
       {'vendor=':'PWD'}, 
       {'online':'Yes'}]}} 


conf_type = raw_input("Enter the conf type: ") 
option = raw_input("Enter the option: ") 
number = raw_input("Enter the number for validation: ") 

dict_options = dict_conf[conf_type] 
option_list = dict_options[option] 

for elem_dict in option_list: 
    if 'number' in elem_dict.keys(): 
     if elem_dict['number'] == number: 
      print "You entered a valid number, it is: " + number 
相關問題