开发者

Converting Tuple to Dictionary

i'm parsing an XML file and getting a tuple in return. i converted the tuple to str and then to dictiona开发者_Python百科ry. i want to get the key and value for Lanestat. for eg: Lanestat, key 1 and get value 2. but the code is not elegant, appreciate any advice. tq

xml:

- <Test>
- <Default_Config>
  <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}</LINK> 
  <Lanestat>{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}</Lanestat> 
  </Default_Config>
  </Test>

output:

('LINK', '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
('Lanestat', '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
<type 'tuple'>
<type 'str'>
<type 'dict'>
2

code:

import elementtree.ElementTree as ET 

tree = ET.parse("dict1.xml") 
doc = tree.getroot() 

for elem in doc.findall('Default_Config/LINK'): 
    a=elem.tag, elem.text 
    print a 

for elem in doc.findall('Default_Config/Lanestat'): 
    a=elem.tag, elem.text 
    print a
    print type(a)
    b=a[1]
    print type(b)
    c=eval(b)
    print type(c)
    print c[1]


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']}])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜