我有一个复杂的字典结构,我想通过一个键列表访问,以解决正确的项目.
dataDict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
maplist = ["a", "r"]
Run Code Online (Sandbox Code Playgroud)
要么
maplist = ["b", "v", "y"]
Run Code Online (Sandbox Code Playgroud)
我已经制作了以下代码,但是我确信如果有人有想法,有更好更有效的方法.
# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):
for k in mapList: dataDict = dataDict[k]
return dataDict
# Set a given data in a dictionary with position provided as a list
def …
Run Code Online (Sandbox Code Playgroud) 有没有办法为嵌套的python词典定义XPath类型查询.
像这样的东西:
foo = {
'spam':'eggs',
'morefoo': {
'bar':'soap',
'morebar': {'bacon' : 'foobar'}
}
}
print( foo.select("/morefoo/morebar") )
>> {'bacon' : 'foobar'}
Run Code Online (Sandbox Code Playgroud)
我还需要选择嵌套列表;)
这可以通过@ jellybean的解决方案轻松完成:
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")
Run Code Online (Sandbox Code Playgroud)
[编辑2016]这个问题和接受的答案是古老的.较新的答案可能比原始答案更好地完成工作.但是我没有测试它们所以我不会改变接受的答案.