簡體   English   中英

在Python中訪問字典中的列表

[英]Accessing the list within a dictionary in 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這個詞?

謝謝

如您提到的, 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'

如果您可以信任輸入,則可以對列表的字符串表示形式進行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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM