Search code examples
python-3.xdictionaryflaskflask-restful

Access a dictionary value based on the list of keys


I have a nested dictionary with keys and values as shown below.

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

Currently, I have a python method which returns me the route based on keys to get to a 'value'. For example, if I want to access the "1" value, the python method will return me a list of string with the route of the keys to get to "1". Thus it would return me, ["app","Garden", "Flowers"]

I am designing a service using flask and I want to be able to return a json output such as the following based on the route of the keys. Thus, I would return an output such as below.

      {
         "id": "1",                                
         "state": "fresh"
      }

The Problem:

I am unsure on how to output the result as shown above as I will need to parse the dictionary "j" in order to build it? I tried something as the following.

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".

Can someone please help me to build the dictionary which I would send to the jsonify method. Any help would be appreciated.


Solution

  • Hope this is what you are asking:

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