Search code examples
pythonelementtreevariable-variables

Variable variables for use in Element Tree Python


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


Solution

  • 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.