KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Is there a way to define a XPath type query for nested python dictionaries. Something like this: foo = { 'spam':'eggs', 'morefoo': { 'bar':'soap', 'morebar': {'bacon' : 'foobar'} } } print( foo.select("/morefoo/morebar") ) >> {'bacon' : 'foobar'} I also needed to select nested lists ;) This can be done easily with @jellybean's solution: def xpath_get(mydict, path): elem = mydict try: for x in path.strip("/").split("/"): try: x = int(x) elem = elem[x] except ValueError: elem = elem.get(x) except: pass return elem foo = { 'spam':'eggs', 'morefoo': [{ 'bar':'soap', 'morebar': { 'bacon' : { 'bla':'balbla' } } }, 'bla' ] } print xpath_get(foo, "/morefoo/0/morebar/bacon") [EDIT 2016] This question and the accepted answer are ancient. The newer answers may do the job better than the original answer. However I did not test them so I won't change the accepted answer.
Tags (comma-separated)
Save Edits
Cancel