[英]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
来解析该文件,然后使用find
, findall
和iter
访问该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")
的问题。
我的问题是,如何从上面的词典而不是单个字母中整体获得props
, char
, env
或sets
这个词?
谢谢
如您提到的, 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.