Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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

share|improve this question
up vote 1 down vote accepted

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.

share|improve this answer
    
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: 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.