xml -> dict: lxml faq solution inadequate

Johann Spies johann.spies at gmail.com
Wed Mar 2 07:38:28 EST 2011


In the lxml-faq I read:

How can I map an XML tree into a dict of dicts?

I'm glad you asked.

def recursive_dict(element):
     return element.tag, \
            dict(map(recursive_dict, element)) or element.text

However this does not work where you have xml-elements where there are
more than one child on the same level.  For example:

<keywords count="4">
<keyword>Bayesian nonparametric statistics</keyword>
<keyword>Frailty modeling</keyword>
<keyword>Poly urn sampling</keyword>
<keyword>Proportional hazards model</keyword>
</keywords>

results in

>>> alys[100]['item']['keywords']
{'keyword': 'Proportional hazards model'}

 How do I get it to give me the following result?

{'keywords': [
{'keyword': 'Bayesian nonparametric statistics'},
{'keyword': 'Frailty modeling'},
{'keyword': 'Poly urn sampling'},
{'keyword': 'Proportional hazards model'}
]}

Regards
Johann
-- 
 May grace and peace be yours in abundance through the full knowledge of God
and of Jesus our Lord!  His divine power has given us everything we need for
life and godliness through the full knowledge of the one who called us by
his own glory and excellence.
                                                    2 Pet. 1:2b,3a
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110302/bfd2c421/attachment.html>


More information about the Python-list mailing list