Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3353762
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T02:11:27+00:00 2026-05-18T02:11:27+00:00

I have the following function which does a crude job of parsing an XML

  • 0

I have the following function which does a crude job of parsing an XML file into a dictionary.

Unfortunately, since Python dictionaries are not ordered, I am unable to cycle through the nodes as I would like.

How do I change this so it outputs an ordered dictionary which reflects the original order of the nodes when looped with for.

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

Outputs:

{'root': {
    'a': ['1'],
    'aa': [{'b': [{'c': ['2']}, '2']}],
    'aaaa': [{'bb': ['4']}],
    'aaa': ['3'],
    'aaaaa': ['5']
}}

a
aa
aaaa
aaa
aaaaa

How can I implement collections.OrderedDict so that I can be sure of getting the correct order of the nodes?

XML file for reference:

<root>
    <a>1</a>
    <aa>
        <b>
            <c>2</c>
        </b>
        <b>2</b>
    </aa>
    <aaa>3</aaa>
    <aaaa>
        <bb>4</bb>
    </aaaa>
    <aaaaa>5</aaaaa>
</root>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T02:11:27+00:00Added an answer on May 18, 2026 at 2:11 am

    You could use the new OrderedDictdict subclass which was added to the standard library’s collections module in version 2.7✶. Actually what you need is an Ordered+defaultdict combination which doesn’t exist — but it’s possible to create one by subclassing OrderedDict as illustrated below:

    ✶ If your version of Python doesn’t have OrderedDict, you should be able use Raymond Hettinger’s Ordered Dictionary for Py2.4 ActiveState recipe as the base class instead.

    import collections
    
    class OrderedDefaultdict(collections.OrderedDict):
        """ A defaultdict with OrderedDict as its base class. """
    
        def __init__(self, default_factory=None, *args, **kwargs):
            if not (default_factory is None or callable(default_factory)):
                raise TypeError('first argument must be callable or None')
            super(OrderedDefaultdict, self).__init__(*args, **kwargs)
            self.default_factory = default_factory  # called by __missing__()
    
        def __missing__(self, key):
            if self.default_factory is None:
                raise KeyError(key,)
            self[key] = value = self.default_factory()
            return value
    
        def __reduce__(self):  # Optional, for pickle support.
            args = (self.default_factory,) if self.default_factory else tuple()
            return self.__class__, args, None, None, iter(self.items())
    
        def __repr__(self):  # Optional.
            return '%s(%r, %r)' % (self.__class__.__name__, self.default_factory, self.items())
    
    def simplexml_load_file(file):
        from lxml import etree
    
        tree = etree.parse(file)
        root = tree.getroot()
    
        def xml_to_item(el):
            item = el.text or None
            child_dicts = OrderedDefaultdict(list)
            for child in el.getchildren():
                child_dicts[child.tag].append(xml_to_item(child))
            return collections.OrderedDict(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)
    

    The output produced from your test XML file looks like this:

    {'root':
        OrderedDict(
            [('a', ['1']),
             ('aa', [OrderedDict([('b', [OrderedDict([('c', ['2'])]), '2'])])]),
             ('aaa', ['3']),
             ('aaaa', [OrderedDict([('bb', ['4'])])]),
             ('aaaaa', ['5'])
            ]
        )
    }
    
    a
    aa
    aaa
    aaaa
    aaaaa
    

    Which I think is close to what you want.

    Minor update:

    Added a __reduce__() method which will allow the instances of the class to be pickled and unpickled properly. This wasn’t necessary for this question, but came up in a similar one.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following function which creates a std::vector of iterators into another container:
I have a function which does the following: When the function is called and
I have a function which does the following loop many, many times: for cluster=1:max(bins),
I have the following (crude) function, which continually watches a directory for new files
I have a certain function which does the following in certain cases: raise Exception,
I have the following code which does a function similar to the way the
I have the following function which accepts text and a word count and if
I have the following function which sets up the GUI. public void go() {
I have the following function which works very well within a $(document).ready(function(){ $('.threadWrapper >
I have the following function in a PHP script, which returns and API call:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.