Sam Sam - 5 months ago 9
Python Question

Create Dictionary List from XML in Python

This is the sample XML.

<?xml version="1.0" encoding="UTF-8"?>
<Test plan_name="test">
<Big bro="S7" sys="lolipop">
<Work name="first"></Work>
<Work name="second"></Work>
</Big>
<Big bro="S6" sys="kitkat">
<Work name="trird"></Work>
<Work name="fourth"></Work>
</Big>
</Test>


My target is to create dictionary with each work name and keep it in a list.

This is my sample code:

import xml.etree.ElementTree as ET

tree = ET.parse(line[0].rstrip()+'/stack.xml')
root = tree.getroot()

total=[]

for child in root.findall('Big'):
test=child.attrib
for children in child:
test.update(children.attrib)
total.append(test)
print total


Expected output:


[{'bro': 'S7', 'sys': 'lolipop', 'name': 'first'}, {'bro': 'S7', 'sys': 'lolipop', 'name': 'second'}, {'bro': 'S6', 'sys': 'kitkat', 'name': 'third'}, {'bro': 'S6', 'sys': 'kitkat', 'name': 'fourth'}]


But My Output looks like this:


[{'bro': 'S7', 'sys': 'lolipop', 'name': 'second'}, {'bro': 'S7', 'sys': 'lolipop', 'name': 'second'}, {'bro': 'S6', 'sys': 'kitkat', 'name': 'fourth'}, {'bro': 'S6', 'sys': 'kitkat', 'name': 'fourth'}]


Help me out please.
Thank you

Answer

You modify your test dict in-place which result in a modification of the previously inserted reference in total as well.
It should work by creating a copy of it before updating it:

...
for child in root.findall('Big'):
  test=child.attrib
  for children in child:    
    testCopy = dict(test)
    testCopy.update(children.attrib)
    total.append(testCopy)
print(total)
...
Comments