2013-09-30 113 views
1

我感覺難住並尋求幫助。我試圖訪問位於字典內部的數組內部的字典中的數據。見下:訪問數據嵌入字典中的數組在字典中

{ 
    'files': [ 
     { 
      'type': 'diskDescriptor', 
      'name': '[VM] VM1/VM1.vmdk', 
      'key': 4, 
      'size': 0 
     }, 
     { 
      'type': 'diskExtent', 
      'name': '[VM] VM1/VM1-flat.vmdk', 
      'key': 5, 
      'size': 32457621504 
     } 
    ], 
    'capacity': 32505856, 
    'label': 'Hard disk 1', 
    'descriptor': '[VM] VM1/VM1.vmdk', 
    'committed': 31696896, 
    'device': { 
     'summary': '32,505,856 KB', 
     '_obj': <pysphere.vi_property.VIProperty object at 0x17442910>, 
     'unitNumber': 0, 
     'key': 2000, 
     'label': 'Hard disk 1', 
     'type': 'VirtualDisk', 
     'capacityInKB': 32505856 
    } 
} 

如果我想要訪問,讓我們說描述符的關鍵值,我將如何去與Python這個?出於某種原因,我嘗試過的所有組合都不起作用。

任何幫助和指導,將不勝感激,如果需要更多信息,我可以提供。謝謝。

回答

3

讓我們打電話給你的主詞典鮑勃,因爲我喜歡鮑勃:

bob['files'] #get you the list with second dictionary 

bob['files'][0] #get you the first item in the list, which is the nested 2nd dictionary 

bob['files'][0]['type'] == 'diskDescriptor' 
+0

太好了!感謝您的及時迴應。但是如果我想獲得'capacityInKB'或'label'(位於'device'下)呢?由於它不在數組中,因此無法使用[]和指定的項目來獲取它。例如 - bob ['files'] [2] ['label']或bob ['files'] [3] ['capacityInKB'] ... – Paul

+0

沒關係 - 我提出了另外一個問題。再次感謝! – Paul

+0

你總是可以在ipython中試試這些,使調試過程變得更加簡單,如果這是你的選擇。只需一步一步打印出來,並且很快就會開始有意義。 – gregb212