0

I'm creating an XML DOM using python's Elementtree module, and it seems that it uses variables as nodes. My question is, how do I create unique varible names so that the nodes are persistent for the DOM if I'm adding records to the DOM in a loop. Sample code below.

someList =[1,2,3,4,5]
root = Element('root')
records = SubElement(root, 'records')

for idx, num in enumerate(someList):
    record+idx = SubElement(records, 'record')

Hopefully this makes sense. Any help or advice would be greatly appreciated

Jacksgrin
  • 85
  • 1
  • 11

1 Answers1

1

The correct answer for this is to store these objects in a dict, not to dynamically name them, ex:

data = dict()
for idx, num in enumerate(someList):
    data['record{}'.format(idx)] = SubElement(records, 'record')

Looking ahead a bit, this will also make it much easier to reference these same objects later, to iterate over them, etc.

dylrei
  • 1,728
  • 10
  • 13
  • Could you elaborate on the syntax of having brackets inside of a dictionary key? I am unfamiliar with using them that way. Thank you for your answer, by the way. – Jacksgrin Jan 13 '15 at 18:06
  • 1
    @Jacksgrin Inside of a string, the braces are an insert point for the argument passed into .format(). So, 'hello, {}'.format('world') would yield 'hello, world' See: https://mkaz.com/2012/10/10/python-string-format/ – dylrei Jan 13 '15 at 18:18
  • Can I use these variable variables stored in the dictionary to set subchildren or text? For example, could I now do: "record{}format(idx).text = record1value" – Jacksgrin Jan 13 '15 at 18:28
  • @Jacksgrin Absolutely, but with a small fix on syntax. What's stored in the dict is a reference to your object. So if you can reference it correctly, it's exactly like if you referred to it by name. If the dict is called "d" and the index when you stored a record was 5, you can refer to it as d['record5'] going forward. You could also get it by index, ex: d['record{}'.format(idx)] – dylrei Jan 13 '15 at 18:39