Iterating through xml in python through KeyError
<p>My Xml :</p>

<pre><code>&lt;books&gt;
&lt;book name="goodbook" cost="10" color="green"&gt;&lt;/book&gt;
&lt;book name="badbook" cost="1000" weight="100"&gt;&lt;/book&gt;
&lt;book name="avgbook" cost="99" weight="120"&gt;&lt;/book&gt;
&lt;/books&gt;
</code></pre>

<p>My python code :-</p>

<pre><code>import xml.etree.ElementTree as ET
import sys
doc       = ET.parse("books.xml")
root      = doc.getroot() 
root_new  = ET.Element("books") 
for child in root:
       name                = child.attrib['name']
       cost                = child.attrib['cost']
       color               = child.attrib['color'] #KeyError
       weight              = child.attrib['weight'] #KeyError
       # create "book" here
       book    = ET.SubElement(root_new, "book") 
       book.set("name",name)               
       book.set("cost",cost) 
       book.set("color",color) 
       book.set("weight",weight)
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
</code></pre>

<p>What error am getting :-</p>

<pre><code>python books.py 
Traceback (most recent call last):
  File "books.py", line 10, in &lt;module&gt;
    weight              = child.attrib['weight'] #KeyError
KeyError: 'weight'
</code></pre>

<p>weight and color are throughing keyerror, because while iterating through loop "color" and "weight" attribute not found in all line. i need my out put should be same as input xml :( . 
How can i skip this error and make it same as input xml . Thanks in advance.</p>
