i\'m parsing an XML file and getting a tuple in return. i converted the tuple to str and then to dictionary. i want to get the key and value for Lanestat. for eg: Lanestat, key
You can use ast.literal_eval() to parse the elem.text into a dict safely:
import ast
for elem in doc.findall('Default_Config/Lanestat'):
if elem.tag == 'Lanestat':
val = ast.literal_eval(elem.text)
print type(val), val
print elem.tag, val[1]
Output:
<type 'dict'> {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}
Lanestat 2
Updated: Here is a backport of literal_eval to Python 2.4/2.5, I've pasted the code here to fix a minor formatting issue:
from compiler import parse
from compiler.ast import *
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, numbers, tuples,
lists, dicts, booleans, and None.
"""
_safe_names = {'None': None, 'True': True, 'False': False}
if isinstance(node_or_string, basestring):
node_or_string = parse(node_or_string, mode='eval')
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.node
def _convert(node):
if isinstance(node, Const) and isinstance(node.value,
(basestring, int, float, long, complex)):
return node.value
elif isinstance(node, Tuple):
return tuple(map(_convert, node.nodes))
elif isinstance(node, List):
return list(map(_convert, node.nodes))
elif isinstance(node, Dict):
return dict((_convert(k), _convert(v)) for k, v
in node.items)
elif isinstance(node, Name):
if node.name in _safe_names:
return _safe_names[node.name]
elif isinstance(node, UnarySub):
return -_convert(node.expr)
raise ValueError('malformed string')
return _convert(node_or_string)
print literal_eval("(1, [-2, 3e10, False, True, None, {'a': ['b']}])")
Output:
(1, [-2, 30000000000.0, False, True, None, {'a': ['b']}])