Xpath like query for nested python dictionaries

后端 未结 10 1651
情话喂你
情话喂你 2020-12-02 15:45

Is there a way to define a XPath type query for nested python dictionaries.

Something like this:

foo = {
  \'spam\':\'eggs\',
  \'morefoo\': {
               


        
10条回答
  •  自闭症患者
    2020-12-02 16:15

    Not exactly beautiful, but you might use sth like

    def xpath_get(mydict, path):
        elem = mydict
        try:
            for x in path.strip("/").split("/"):
                elem = elem.get(x)
        except:
            pass
    
        return elem
    

    This doesn't support xpath stuff like indices, of course ... not to mention the / key trap unutbu indicated.

提交回复
热议问题