Python 将xml字段打印为字典

Python 将xml字段打印为字典,python,xml,dictionary,return,Python,Xml,Dictionary,Return,这是我使用的xml文件: <fields> <input_layer name = "Pocket_Substation"/> <output_layer name = "sub_substation"/> <field_mapping> <field input_name = "dat" output_name="date" /> <field input_name = "Type" output_name=

这是我使用的xml文件:

<fields>
<input_layer name = "Pocket_Substation"/>
<output_layer name = "sub_substation"/>
<field_mapping>
    <field input_name = "dat"  output_name="date" />
    <field input_name = "Type"  output_name="type"/>
    <field input_name = "Class"  output_name="class"/>
    <field input_name = "Land"  output_name="land"/>
    <field input_name = "status"  output_name="status"/>
    <field input_name = "descrp"  output_name="description"/>
    <field input_name = "Loc"  output_name="location"/>
    <field input_name = "voltage" output_name="voltage"/>
    <field input_name = "name"  output_name="owner_name"/>
    <field input_name = "Remarks"  output_name="remarks"/>
</field_mapping>
</fields>
代码如下:

import xml.etree.ElementTree as ET

def read_field(xml_node, name):
    return [child.get(name) for child in xml_node.iter('field')]

def read_map(xml_node):
    fields = dict()

    for child in xml_node:
        if child.tag == 'field_mapping':
            fields = {field_name : read_field(child, field_name) for field_name 
                 in ['input_name','output_name']}

            return{
                fields['input_name']:fields['output_name']
                }

tree = ET.parse('substation.xml')
root = tree.getroot()
print(read_map(root))

您太快完成了执行,请尝试以下操作:

def read_map(xml_node):
    result = {}
    for child in xml_node:
        result[child.get('output_name') ] = child.get('input_name') 
    return result

tree = ET.parse('substation.xml')
root = tree.getroot()
print(read_map(root.find('field_mapping')))

这一行就是问题所在:
return{fields['input\u name']:fields['output\u name']}

这表示“返回一个dict,其中包含一个条目,其键等于输入名称列表,值等于输出名称列表”。Python接着抱怨,因为列表不能是dict键

您可能想做的是返回一个dict,将输入名称映射到输出名称。为此,将两个列表压缩在一起(创建一个元组列表),然后将其转换为dict,dict将把每个元组解释为键/值对

因此,将上述行替换为以下内容:


返回dict(zip(字段['input\u name',字段['output\u name'))

当您更新了问题的某些部分时,让我更改代码
def read_map(xml_node):
    result = {}
    for child in xml_node:
        result[child.get('output_name') ] = child.get('input_name') 
    return result

tree = ET.parse('substation.xml')
root = tree.getroot()
print(read_map(root.find('field_mapping')))