Xpath like query for nested python dictionaries

后端 未结 10 1682
情话喂你
情话喂你 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 15:52

    If terseness is your fancy:

    def xpath(root, path, sch='/'):
        return reduce(lambda acc, nxt: acc[nxt],
                      [int(x) if x.isdigit() else x for x in path.split(sch)],
                      root)
    

    Of course, if you only have dicts, then it's simpler:

    def xpath(root, path, sch='/'):
        return reduce(lambda acc, nxt: acc[nxt],
                      path.split(sch),
                      root)
    

    Good luck finding any errors in your path spec tho ;-)

提交回复
热议问题