【问题标题】:Looping over multiple dictionaries and not just the last dictionary in python循环遍历多个字典,而不仅仅是 python 中的最后一个字典
【发布时间】:2012-11-26 14:20:48
【问题描述】:

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

但是,当我尝试循环遍历“输出”字典以查找所有“活动”键及其包含的值时。它只返回一个值,即在架构中找到的最后一个“Active”的值。

所以我的问题是,我如何在所有这些字典上进行迭代或 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'}

通过for循环:

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

No
No

期望的输出:

Yes
No

【问题讨论】:

  • 您能否提供一个示例输入/预期输出?
  • 据我了解。您的问题似乎是您正在覆盖字典中的“活动”键。因此,每次您看到“活动”时,您都会将值分配给output['Active'],并且您正在覆盖以前的值。这就是为什么你只得到最后一个。
  • 我明白你的意思 dado_eyad ,但我能做些什么来保持字典的名称相同,但在提到的资产上找到的每组信息都有多组值?

标签: python xml dictionary


【解决方案1】:

两个问题:

  1. 您正在覆盖每个 AssetEquipment 的输出字典。它适用于内联 print 语句,但您以后不能循环遍历结果。您应该将每个输出字典保存在一个列表中。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多