1

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

2
  • What is the ET variable? ElementTree? Commented Jun 23, 2016 at 5:45
  • yes. import xml.etree.ElementTree as ET will be above. Commented Jun 23, 2016 at 5:46

1 Answer 1

1

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)
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.