根据键列表访问字典值
Access a dictionary value based on the list of keys
我有一个包含键和值的嵌套字典,如下所示。
j = {
"app": {
"id": 0,
"status": "valid",
"Garden": {
"Flowers":
{
"id": "1",
"state": "fresh"
},
"Soil":
{
"id": "2",
"state": "stale"
}
},
"BackYard":
{
"Grass":
{
"id": "3",
"state": "dry"
},
"Soil":
{
"id": "4",
"state": "stale"
}
}
}
}
目前,我有一个 python 方法,该方法 return 为我提供了基于键的路线以到达 'value'。例如,如果我想访问“1”值,python 方法将 return 一个字符串列表,其中包含到达“1”的键的路径。因此它会 return 我,["app","Garden", "Flowers"]
我正在使用 flask 设计一个服务,我希望能够 return json 根据键的路径输出如下所示。因此,我会 return 如下所示的输出。
{
"id": "1",
"state": "fresh"
}
问题:
我不确定如何输出如上所示的结果,因为我需要解析字典 "j" 才能构建它?
我尝试了以下方法。
def build_dictionary(key_chain):
d_temp = list(d.keys())[0]
...unsure on how to
#Here key_chain contains the ["app","Garden", "Flowers"] sent to from the method which parses the dictionary to store the key route to the value, in this case "1".
有人可以帮助我构建我将发送给 jsonify 方法的词典。任何帮助将不胜感激。
希望这就是您要问的:
def build_dictionary(key_chain, j):
for k in key_chain:
j = j.get(k)
return j
kchain = ["app","Garden", "Flowers"]
>>> build_dictionary(kchain, j)
{'id': '1', 'state': 'fresh'}
我有一个包含键和值的嵌套字典,如下所示。
j = {
"app": {
"id": 0,
"status": "valid",
"Garden": {
"Flowers":
{
"id": "1",
"state": "fresh"
},
"Soil":
{
"id": "2",
"state": "stale"
}
},
"BackYard":
{
"Grass":
{
"id": "3",
"state": "dry"
},
"Soil":
{
"id": "4",
"state": "stale"
}
}
}
}
目前,我有一个 python 方法,该方法 return 为我提供了基于键的路线以到达 'value'。例如,如果我想访问“1”值,python 方法将 return 一个字符串列表,其中包含到达“1”的键的路径。因此它会 return 我,["app","Garden", "Flowers"]
我正在使用 flask 设计一个服务,我希望能够 return json 根据键的路径输出如下所示。因此,我会 return 如下所示的输出。
{
"id": "1",
"state": "fresh"
}
问题:
我不确定如何输出如上所示的结果,因为我需要解析字典 "j" 才能构建它? 我尝试了以下方法。
def build_dictionary(key_chain):
d_temp = list(d.keys())[0]
...unsure on how to
#Here key_chain contains the ["app","Garden", "Flowers"] sent to from the method which parses the dictionary to store the key route to the value, in this case "1".
有人可以帮助我构建我将发送给 jsonify 方法的词典。任何帮助将不胜感激。
希望这就是您要问的:
def build_dictionary(key_chain, j):
for k in key_chain:
j = j.get(k)
return j
kchain = ["app","Garden", "Flowers"]
>>> build_dictionary(kchain, j)
{'id': '1', 'state': 'fresh'}