【问题标题】:Printing the xml fields as dictionary将 xml 字段打印为字典
【发布时间】:2017-10-18 01:49:03
【问题描述】:

这是我使用的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>

我需要字典格式的字段值(输出名称:输入名称)。以下是我打印字典的代码,但程序返回

unhashable type: 'list' error.

代码如下:

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

【问题讨论】:

    标签: python xml dictionary return


    【解决方案1】:

    这行是问题所在:return { fields['input_name']:fields['output_name'] }

    这表示“返回一个包含单个条目的字典,其键等于输入名称列表,值等于输出名称列表”。然后 Python 会抱怨,因为列表不能是 dict 键。

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

    所以将上面的行替换为以下内容:

    return dict(zip(fields['input_name'],fields['output_name']))

    【讨论】:

      【解决方案2】:

      你执行得太快了,试试这个:

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

      【讨论】:

      • 当您更新了问题的某些部分时,让我更改我的代码
      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2016-04-22
      • 2015-05-29
      • 2016-11-11
      相关资源
      最近更新 更多