title: XML parsing in Python with element tree
body: <p>I'm using Python with ElementTree to parse an XML file. I want to be able to make a list of dictionaries containing the information of all the CDs. I can use this list later to gather information, like displaying the title of CDs coming from the USA. The code below is working, but can easily be broken if the <code>YEAR</code> tag is not the last tag of CD. How can I rewrite this code so that tags could be in any order?</p>
  
  <pre><code>from xml.etree.ElementTree import ElementTree
  
  f = open("cd_catalog.xml")
  tree = ElementTree()
  tree.parse(f)
  
  catalog = []
  cd = {}
  for node in tree.iter():
      if node.tag != "CD" and node.tag != "CATALOG":
          tagtext = (node.tag,node.text),
          cd.update(tagtext)
      if node.tag == "YEAR":
          catalog.append(cd)
          cd = {}
  
  for cd in catalog:
      if cd["COUNTRY"] == "USA":
          print("The cd named {0} is from USA".format(cd["TITLE"]))
  </code></pre>
  
  <p>2 entries of the xml file :</p>
  
  <pre><code>&lt;CATALOG&gt;
      &lt;CD&gt;
          &lt;TITLE&gt;Empire Burlesque&lt;/TITLE&gt;
          &lt;ARTIST&gt;Bob Dylan&lt;/ARTIST&gt;
          &lt;COUNTRY&gt;USA&lt;/COUNTRY&gt;
          &lt;COMPANY&gt;Columbia&lt;/COMPANY&gt;
          &lt;PRICE&gt;10.90&lt;/PRICE&gt;
          &lt;YEAR&gt;1985&lt;/YEAR&gt;
      &lt;/CD&gt;
      &lt;CD&gt;
          &lt;TITLE&gt;Hide your heart&lt;/TITLE&gt;
          &lt;ARTIST&gt;Bonnie Tyler&lt;/ARTIST&gt;
          &lt;COUNTRY&gt;UK&lt;/COUNTRY&gt;
          &lt;COMPANY&gt;CBS Records&lt;/COMPANY&gt;
          &lt;PRICE&gt;9.90&lt;/PRICE&gt;
          &lt;YEAR&gt;1988&lt;/YEAR&gt;
      &lt;/CD&gt;
  &lt;/CATALOG&gt;
  </code></pre>