2017-07-05 64 views
0

我創建了一個字典在Python訪問字典中的列表

store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'} 

這是一個XML文件中,所以我用xml.etree.ElementTree解析文件和findfindalliter訪問XML文件和上面的線是我在最後得到的。我用一個for循環訪問XML文件

import xml.etree.ElementTree as xml 

read = xml.parse(xmlFile) 
#xmlFile is the xmlFile directory 

findBase = read.findall('base') 
#'base' and 'type' are the xml.SubElement used in the xml file. 

for child in findBase: 
    findType = child.iter('type') 
    store = child.attrib 
    for types in findType: 
     store[types.attrib.keys()[0]] = types.attrib.values()[0] 
    print store 
    print store.items()[0][1][3] 

不過,現在我想從上面的字典從'assetType'訪問'props'。我嘗試使用store.items()[0][1],我可以得到"['props','char','env','sets']",但是當我做store.items()[0][1][3],而不是得到sets這個詞時,我得到了r。我理解它背後的原因,這是因爲它已將整行註冊爲字符串而不是字符列表。我也試過類似store.get("assetType")這個問題是一樣的。

我的問題是,我怎麼能得到這個詞propscharenvsets從字典中的整個上面,而不是單獨的信嗎?

感謝

+0

'從AST進口literal_eval; literal_eval(「['props','char','env','sets']」)' – idjaw

+0

將XML轉換爲JSON,然後將其作爲字典加載。然後開始一個新的職業,成爲JSON傳道人。 http://www.commitstrip.com/en/2014/05/27/and-thats-how-good-old-xml-disappeared/ – Fabien

回答

0

assetType值是你提到需要被解析成一個列表的字符串。如評論中提到的一些方法來做到這一點。這是一個簡單的JSON方式,不幸的是您的案例非常具體。單引號不是有效的JSON,所以他們必須交換雙打。

>>> import json 
>>> store = {'assetType': "['props','char','env','sets']", 
'Height': '871', 'Project': 'AnimationProject1', 
'Width': '2048', 'FPS': '24', 'Type': 'Animation', 
'Unit': 'cm'} 
>>> json.loads(store['assetType'].replace("'",'"'))[3] 
u'sets' 
0

如果你可以信任的輸入,你可以做你的列表的字符串表示的eval將其轉換爲一個適當的Python列表

store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'} 
asset_types = eval(store['assetType']) 
# Then access the entries in the list 
print asset_types[0] # etc.