1

Basically I need to loop through a python dict and create an xml element tag with the for loop returned values as xml element keys, I.e:

d = {}
d["a"] = "1"
d["b"] = "2"
d["c"] = "what"

root = ET.Element("root")
child = ET.SubElement(root, "child")
for k,v in d.items():
    ET.SubElement(child, "field1", k=v).text = "some value1"
tree = ET.ElementTree(root)
tree.write("logs/filename.xml")

I want the result to look like:

<root><child><field1 a="1" b="2" c="what">some value1</field1></child></root>
1
  • Okay, so what is your question? What happened when you tried the code, and how is that different from the desired result? Please read How to Ask. Commented Aug 27, 2021 at 23:04

1 Answer 1

1

You only add field1 once:

d = dict(a="1", b="2", c="what")
root = ET.Element("root")
child = ET.SubElement(root, "child")
field1 = ET.SubElement(child, "field1")
field1.attrib.update(d)
field1.text = "some value1"
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.