像Xpath一样查询嵌套的python字典 [英] Xpath like query for nested python dictionaries
问题描述
有没有一种方法可以为嵌套的python字典定义XPath类型查询.
Is there a way to define a XPath type query for nested python dictionaries.
类似这样的东西:
foo = {
'spam':'eggs',
'morefoo': {
'bar':'soap',
'morebar': {'bacon' : 'foobar'}
}
}
print( foo.select("/morefoo/morebar") )
>> {'bacon' : 'foobar'}
我还需要选择嵌套列表;)
I also needed to select nested lists ;)
这可以通过@jellybean的解决方案轻松完成:
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")
这个问题和被接受的答案都是古老的.更新的答案可能比原始答案做得更好.但是我没有测试它们,所以我不会更改已接受的答案.
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.
推荐答案
不是很漂亮,但是您可能会使用
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
当然,这不支持xpath之类的索引,更不用说了/
键陷阱unutbu了.
This doesn't support xpath stuff like indices, of course ... not to mention the /
key trap unutbu indicated.
这篇关于像Xpath一样查询嵌套的python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!