I have problem with dictionaries within python, I am currently getting what information I want out of my incoming xml thanks to “Namit Kewat”. And when I print the output it lists all of the things it found, each in its own dictionary, which is good.
However when I try to for loop over the “output” dictionary to find the all of the “Active” keys and the values they contain. It only returns one value, and that is the value of the last “Active” found within the schema.
So my problem is, how can I iterate or for loop etc, over ALL these dictionaries. I want the dictionary to be called “output” and there will be many “AssetEquipment” sections in my incoming xml. If dictionaries are not the way then please advise better solutions. Essentially my goal is to iterate of many “AssetEquipment” to get values and then extend that to cover other things within the xml file like “AssetSupport”. So there is a lot of groups with multiple versions/instances that need.
Thank you.
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
Sample Input (Kept it small as it is too large to post everything):
<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>
Sample Output,
Via Print:
{'Direction': 'Positive', 'Active': 'Yes', 'Room': '18'}
{'Direction': 'Positive', 'Active': 'No', 'Room': '19'}
Via for loop:
def isactive():
for key in output:
print output.get("Active")
No
No
Desired Output:
Yes
No
Two problems:
You’re overwriting the output dictionary for each AssetEquipment. It works with the inline print statement, but you can’t loop over the results later. You should save each output dict in a list.
You need to loop through the result list, not over the keys of a single output dict