来自关键路径的嵌套字典值 [英] Nested dictionary value from key path
问题描述
借助键路径从嵌套字典中获取值,这是dict
:
Get the value from a nested dictionary with the help of key path, here is the dict
:
json = {
"app": {
"Garden": {
"Flowers": {
"Red flower": "Rose",
"White Flower": "Jasmine",
"Yellow Flower": "Marigold"
}
},
"Fruits": {
"Yellow fruit": "Mango",
"Green fruit": "Guava",
"White Flower": "groovy"
},
"Trees": {
"label": {
"Yellow fruit": "Pumpkin",
"White Flower": "Bogan"
}
}
}
该方法的输入参数是点分隔的关键路径,从关键路径="app.Garden.Flowers.white Flower"需要打印'Jasmine'.到目前为止,我的代码:
The input parameter to the method is the key path with dots separated, from the key path = "app.Garden.Flowers.white Flower" need to print 'Jasmine'. My code so far:
import json
with open('data.json') as data_file:
j = json.load(data_file)
def find(element, JSON):
paths = element.split(".")
# print JSON[paths[0]][paths[1]][paths[2]][paths[3]]
for i in range(0,len(paths)):
data = JSON[paths[i]]
# data = data[paths[i+1]]
print data
find('app.Garden.Flowers.White Flower',j)
推荐答案
非常接近.您需要(就像您在评论中一样)以递归方式遍历主JSON对象.您可以通过存储最外面的键/值的结果,然后使用它来获取下一个键/值等,直到您脱离路径为止.
Very close. You need to (as you had in your comment) recursively go through the main JSON object. You can accomplish that by storing the result of the outermost key/value, then using that to get the next key/value, etc. till you're out of paths.
def find(element, JSON):
paths = element.split(".")
data = JSON
for i in range(0,len(paths)):
data = data[paths[i]]
print data
尽管如此,您仍然需要提防KeyErrors.
You still need to watch out for KeyErrors though.
这篇关于来自关键路径的嵌套字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!