Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can this function be rewritten to implement OrderedDict?
    primarykey
    data
    text
    <p>I have the following function which does a crude job of parsing an XML file into a dictionary.</p> <p>Unfortunately, since Python dictionaries are not ordered, I am unable to cycle through the nodes as I would like.</p> <p>How do I change this so it outputs an ordered dictionary which reflects the original order of the nodes when looped with 'for'.</p> <pre><code>def simplexml_load_file(file): import collections from lxml import etree tree = etree.parse(file) root = tree.getroot() def xml_to_item(el): item = None if el.text: item = el.text child_dicts = collections.defaultdict(list) for child in el.getchildren(): child_dicts[child.tag].append(xml_to_item(child)) return dict(child_dicts) or item def xml_to_dict(el): return {el.tag: xml_to_item(el)} return xml_to_dict(root) x = simplexml_load_file('routines/test.xml') print x for y in x['root']: print y </code></pre> <p>Outputs:</p> <pre class="lang-none prettyprint-override"><code>{'root': { 'a': ['1'], 'aa': [{'b': [{'c': ['2']}, '2']}], 'aaaa': [{'bb': ['4']}], 'aaa': ['3'], 'aaaaa': ['5'] }} a aa aaaa aaa aaaaa </code></pre> <p>How can i implement collections.OrderedDict so that I can be sure of getting the correct order of the nodes?</p> <p>XML file for reference:</p> <pre class="lang-xml prettyprint-override"><code>&lt;root&gt; &lt;a&gt;1&lt;/a&gt; &lt;aa&gt; &lt;b&gt; &lt;c&gt;2&lt;/c&gt; &lt;/b&gt; &lt;b&gt;2&lt;/b&gt; &lt;/aa&gt; &lt;aaa&gt;3&lt;/aaa&gt; &lt;aaaa&gt; &lt;bb&gt;4&lt;/bb&gt; &lt;/aaaa&gt; &lt;aaaaa&gt;5&lt;/aaaaa&gt; &lt;/root&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload