I have created a dictionary
store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'}
This is within an xml file, so I use xml.etree.ElementTree
to parse the file and find
, findall
and iter
to access the xml files and the above line is what I got at the end. I use a for loop to access the xml file
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]
However, now I would like access 'props'
from 'assetType'
from the dictionary above. I tried using store.items()[0][1]
and I'm able to get "['props','char','env','sets']"
but when I do store.items()[0][1][3]
, instead of getting the word sets
, I get r
instead. I understand the reason behind it, it's because it has registered that whole line as a string instead of a list of characters. I have also tried something like store.get("assetType")
The problem is the same.
My question is, how can I get the word props
, char
, env
or sets
as a whole from the dictionary above instead of individual letters?
Thanks
The assetType
value is a string as you mentioned that needs to be parsed into a list. A couple ways to do it as mentioned in the comments. Here's a simple JSON way that's unfortunately fairly specific to your case. The single quotes have are not valid JSON so they have to be swapped for doubles.
>>> 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'
If you can trust the input you can do an eval
on the string representation of your list to convert it into a proper Python list
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.