Parsing an XML file with elements for keys and values I'm parsing an XML file that is structured like this:

&lt;root&gt;
  &lt;entry&gt;
    &lt;elem1&gt; key &lt;/elem1&gt;
    &lt;elem2&gt; value &lt;/elem2&gt;
  &lt;/entry&gt;
  &lt;entry&gt;
  ....
  &lt;/entry&gt;
&lt;/root&gt;

&lt;/root&gt;


My first code was using .parse() and .getRoot() but I had memory issues (1.5G memory use for 350M file). I solved my problem using an iterator and .clear() after reading this paper.

import xml.etree.ElementTree

myDict = {}

xmlIterator = xml.etree.ElementTree.iterparse('file.xml')

while True:
    try:
        _ , elem1 = next(xmlIterator)
        _ , elem2 = next(xmlIterator)
        _ , _     = next(xmlIterator)

    except StopIteration:
        break

    myDict[elem1.text]=elem2

    elem1.clear()
    elem2.clear()
    _.clear()


The issue is I need to access several children at the same time:


The first one is my key &lt;elem1&gt;
The second one is the value I need &lt;elem2&gt;
The third is not relevant &lt;entry&gt;


I would like to know if this is a good practice, or if there is a better way to do that (better performance or readability).

I also tried to follow the "Easier to ask for forgiveness than permission" principle with the exception block for ending the loop, but I'm not sure about multiple statements in the same exception block.

In fact, I also don't understand why the third element I get with next() is &lt;entry&gt;.
This isn't the answer you want. But, _ is most commonly the discard variable.
You use it when you don't want to use the variable, but you need to specify a variable.
Take:

for _ in range(10):
    print('hi')


We don't want the output from the range, we just want to print 'hi' ten times.
And so you should not use this for the variable you use .clear() on.

I'd use zip rather than the try-except.
Sure there's Look Before You Leap (LBYL) and Easier to Ask for Forgiveness than Permission (EAFP).
But you don't need to use either here.
Also, by using zip you can change your while loop to a for loop too.

And so you should be able to get something like:

import xml.etree.ElementTree

elements = {}
xml_iterator = xml.etree.ElementTree.iterparse('file.xml')

for (_, elem1), (_, elem2), (_, elem3) in zip(xml_iterator, xml_iterator, xml_iterator):
    elements[elem1.text] = elem2
    elem1.clear()
    elem2.clear()
    elem3.clear()