根据键列表访问字典值

时间:2019-05-06 20:43:59

标签: python-3.x dictionary flask flask-restful

我有一个嵌套的字典,其中包含键和值,如下所示。

   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方法,该方法根据键向我返回到达“值”的路由。例如,如果我要访问“ 1”值,则python方法将为我返回一个字符串列表,其中包含到达“ 1”的键的路由。因此它将返回我["app","Garden", "Flowers"]

我正在设计一个使用flask的服务,我希望能够根据键的路由返回诸如以下内容的json输出。因此,我将返回如下输出。

      {
         "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方法。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

希望这是您的要求:

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'}