为什么在遍历字典时会出现错误

2024-06-16 11:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的初学者,很难理解为什么在遍历从XML文件获得的字典时,我在尝试搜索所需的键时会出现错误,我还应该提到,我仍然得到了我想要的结果,但不知怎么的,我总是收到一个错误

    import os
    import shelve
    import xml.etree.ElementTree as et

    shelfFile = shelve.open('xml_data')
    base_path = os.path.dirname(os.path.realpath(__file__))

    xml_file = os.path.join(base_path, "data\\nrm_icg_catalog.xml")

    tree = et.parse(xml_file)

    root = tree.getroot()

    elements = ['Name','WBS']

    for child in root:
        for itemGroup1 in child:
            for item in elements:
                print(itemGroup1.attrib[item])

结果显示错误消息:

Facilitating Works
0
Substructure
1
Superstructure
2
Internal Finish
3
Fittings
4
Services
5
Prefabs
6
Works to Existing Building
7
External Works
8
MC Prelims
9
MC OH and P
10
Traceback (most recent call last):
  File "c:/Users/Dodzi Agbenorku/OneDrive/Training Files/Programming Lessons/Python/xmlExcel/app.py", line 22, in <module>
    print(itemGroup1.attrib[item])
KeyError: 'Name'

下面是我正在使用的xml文件的一小部分:

<?xml version="1.0" encoding="utf-8"?>
<Takeoff xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://download.autodesk.com/us/navisworks/schemas/nw-TakeoffCatalog-10.0.xsd">
    <Catalog>
        <ItemGroup Name="Facilitating Works" WBS="0" CatalogId="32b4ab2d-6fe8-4c45-9872-c8ea68c0c4de">
            <ItemGroup Name="Hazardous Materials" WBS="1" CatalogId="2fdb6bd1-b2d1-4167-a74d-da818183a156">
                <ItemGroup Name="Material Removal" WBS="1" CatalogId="ccc8a515-4152-400c-a72e-6fd78561325e">
                    <Item Name="Material Details" WBS="1" Transparency="0.3" Color="-15161029" LineThickness="0.1" CatalogId="c0a7de26-6bc3-491e-b3c7-3ff5b560eeaf">
                        <VariableCollection>
                            <Variable Name="Length" Formula="=ModelLength" Units="Meter" />
                            <Variable Name="Width" Formula="=ModelWidth" Units="Meter" />
                            <Variable Name="Thickness" Formula="=ModelThickness" Units="Meter" />
                            <Variable Name="Height" Formula="=ModelHeight" Units="Meter" />
                            <Variable Name="Perimeter" Formula="=ModelPerimeter" Units="Meter" />
                            <Variable Name="Area" Formula="=ModelArea" Units="SquareMeter" />

任何帮助都将不胜感激


Tags: pathnameinimportos错误xmlvariable
1条回答
网友
1楼 · 发布于 2024-06-16 11:24:40

发生此错误的原因是,对于某些节点,Name不在attrib中,后者是一个字典

itemGroup1.attrib.get(item)代替itemGroup1.attrib[item]。如果键不存在,它将返回值None,并且不会抛出错误

相关问题 更多 >