将元组转换为字典

将元组转换为字典

本文介绍了将元组转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析XML文件并获得一个元组作为回报.我将元组转换为str,然后转换为字典.我想获取Lanestat的键和值.例如:Lanestat,键1并获取值2.但是代码并不优雅,请多多指教. tq

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 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>

输出:

('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

代码:

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]

推荐答案

您可以使用 ast.literal_eval() 以将 elem.text 安全地解析为字典:

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]

输出:

<type 'dict'> {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}
Lanestat 2

已更新:这是将literal_eval移植到Python 2.4/2.5 ,我在此处粘贴了代码以解决一个较小的格式问题:

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

输出:

(1, [-2, 30000000000.0, False, True, None, {'a': ['b']}])

这篇关于将元组转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:35