Skip to content

Instantly share code, notes, and snippets.

@jacobian
Created January 25, 2011 20:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jacobian/795571 to your computer and use it in GitHub Desktop.
Save jacobian/795571 to your computer and use it in GitHub Desktop.
Convert an lxml.etree node tree into a dict.
def elem2dict(node):
"""
Convert an lxml.etree node tree into a dict.
"""
d = {}
for e in node.iterchildren():
key = e.tag.split('}')[1] if '}' in e.tag else e.tag
value = e.text if e.text else elem2dict(e)
d[key] = value
return d
@fedorovmn
Copy link

The function doesn't convert root tag into a dict. So you should care about a root tag outside a recursion if you need it.
for ex. testtest2 will be converted to {a: test1, b: test2} NOT {'root': {a: test1, b: test2}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment