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

  • SEARCH
  • Home
  • 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 3335704
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T00:02:56+00:00 2026-05-18T00:02:56+00:00

i have the following function, which doe a basic job of mapping an lxml

  • 0

i have the following function, which doe a basic job of mapping an lxml object to a dictionary…

from lxml import etree 

tree = etree.parse('file.xml')
root = tree.getroot()

def xml_to_dict(el):
    d={}
    if el.text:
        print '***write tag as string'
        d[el.tag] = el.text
    else:
        d[el.tag] = {}
    children = el.getchildren()
    if children:
        d[el.tag] = map(xml_to_dict, children)
    return d

    v = xml_to_dict(root)

at the moment it gives me….

>>>print v
{'root': [{'a': '1'}, {'a': [{'b': '2'}, {'b': '2'}]}, {'aa': '1a'}]}

but i would like….

>>>print v
{'root': {'a': ['1', {'b': [2, 2]}], 'aa': '1a'}}

how do i rewrite the function xml_to_dict(el) so that i get the required output?

here’s the xml i’m parsing, for clarity.

<root>
    <a>1</a>
    <a>
        <b>2</b>
        <b>2</b>
    </a>
    <aa>1a</aa>
</root>

thanks 🙂

  • 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-18T00:02:56+00:00Added an answer on May 18, 2026 at 12:02 am

    Well, map() will always return a list, so the easy answer is “don’t use map()“. Instead, build a dictionary like you already are, by looping over children and assigning the result of xml_to_dict(child) to the dictionary key you want to use. It looks like you want to use the tag as the key and have the value be a list of items with that tag, so it would become something like:

    import collections
    from lxml import etree
    
    tree = etree.parse('file.xml')
    root = tree.getroot()
    
    def xml_to_dict(el):
        d={}
        if el.text:
            print '***write tag as string'
            d[el.tag] = el.text
        child_dicts = collections.defaultdict(list)
        for child in el.getchildren():
            child_dicts[child.tag].append(xml_to_dict(child))
        if child_dicts:
            d[el.tag] = child_dicts
        return d
    
    xml_to_dict(root)
    

    This leaves the tag entry in the dict as a defaultdict; if you want a normal dict for some reason, use d[el.tag] = dict(child_dicts). Note that, like before, if a tag has both text and children the text won’t appear in the dict. You may want to think about a different layout for your dict to cope with that.

    EDIT:

    Code that would produce the output in your rephrased question wouldn’t recurse in xml_to_dict — because you only want a dict for the outer element, not for all child tags. So, you’d use something like:

    import collections
    from lxml import etree
    
    tree = etree.parse('file.xml')
    root = tree.getroot()
    
    def xml_to_item(el):
        if el.text:
            print '***write tag as string'
            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)}
    
    print xml_to_dict(root)
    

    This still doesn’t handle tags with both text and children sanely, and it turns the collections.defaultdict(list) into a normal dict so the output is (almost) as you expect:

    ***write tag as string
    ***write tag as string
    ***write tag as string
    ***write tag as string
    ***write tag as string
    ***write tag as string
    {'root': {'a': ['1', {'b': ['2', '2']}], 'aa': ['1a']}}
    

    (If you really want integers instead of strings for the text data in the b tags, you’ll have to explicitly turn them into integers somehow.)

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

Sidebar

Related Questions

So: I have the following function, adapted from a formula found online, which takes
I have the following JavaScript code: Link In which the function makewindows does not
I have the following javascript code, which loads without error, however the update function
I have the following function that is pulling data from a database. The ajax
I have the following function: CREATE FUNCTION fGetTransactionStatusLog ( @TransactionID int ) RETURNS varchar(8000)
Let's say I have the following function: sumAll :: [(Int,Int)] -> Int sumAll xs
I have the following Oracle function: function get_job_no return number is V_job_no number; begin
Say I have the following code: function One() {} One.prototype.x = undefined; function Two()
I have the following intentionally trivial function: void ReplaceSome(ref string text) { StringBuilder sb
I have the following serialization method: Private Function SerializeData(ByVal data As cData) As String

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.