在多个字典上循环,而不仅仅是python中的最后一个字典



我对python中的字典有问题,由于"Namit Kewat",我目前正在从传入的xml中获得我想要的信息。当我打印输出时,它会列出它找到的所有东西,每个都在自己的字典中,这很好。

然而,当我试图在"输出"字典上进行for循环以查找所有"活动"键及其包含的值时。它只返回一个值,即在架构中找到的最后一个"活动"的值。

所以我的问题是,我如何在所有这些字典上迭代或for循环等。我希望字典被称为"输出",并且在我传入的xml中会有许多"AssetEquipment"部分。如果字典不适合,那么请建议更好的解决方案。从本质上讲,我的目标是迭代许多"AssetEquipment"以获得值,然后将其扩展到xml文件中的其他内容,如"AssetSupport"。因此,需要许多具有多个版本/实例的组。

谢谢。

import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
for elem in tree.getiterator():
if elem.tag=='{http://www.namespace.co.uk}AssetEquipment':
output={}
for elem1 in list(elem):
if elem1.tag=='{http://www.namespace.co.uk}Active':
output['Active']=elem1.text
if elem1.tag=='{http://www.namespace.co.uk}Direction':
output['Direction']=elem1.text
if elem1.tag=='{http://www.namespace.co.uk}Location':
for elem2 in list(elem1):
if elem2.tag=='{http://www.namespace.co.uk}RoomLocation':
for elem3 in list(elem2):
if elem3.tag=='{http://www.namespace.co.uk}Room':
output['Room']=elem3.text
print output

样本输入(保持较小,因为它太大而无法发布所有内容):

<AssetEquipment>
<Name>PC123</Name>
<Active>Yes</Active>
<Direction>Positive</Direction>
<Location>
<RoomLocation>
<Room>18</Room>
</RoomLocation>
</Location>
</AssetEquipment>
<AssetEquipment>
<Name>PC256</Name>
<Active>No</Active>
<Direction>Positive</Direction>
<Location>
<RoomLocation>
<Room>19</Room>
</RoomLocation>
</Location>
</AssetEquipment>

样本输出,通过打印:

{'Direction': 'Positive', 'Active': 'Yes', 'Room': '18'}
{'Direction': 'Positive', 'Active': 'No', 'Room': '19'}

环路通过:

def isactive():
for key in output:
print output.get("Active")
No
No

期望输出:

Yes
No

两个问题:

  1. 您正在覆盖每个AssetEquipment的输出字典。它与内联print语句配合使用,但以后不能循环显示结果。您应该将每个输出dict保存在一个列表中。

    results = []
    for elem in tree.getiterator():
    if elem.tag=='{http://www.namespace.co.uk}AssetEquipment':
    output={}
    results.append(output)
    ...
    
  2. 您需要在结果列表中循环,而不是在单个输出dict 的键上循环

    def isactive():
    for output in results:
    print output.get("Active")
    

最新更新