Monday, 1 July 2019

update nested dictionary values from another nested dictionary based on mapping provided in dictionary

I need to write down a method to transform existing nested dictionary values from another nested dictionary , and mapping in between these two dictionary is in another third dictionary.

input_json = { 
              "s0" : 
              {
                 "s1"  :  {
                       "s1_f1":"s1_v1",
                       "s1_f2" : "s1_v2"
                     },
                  "s2":   {
                       "s2_f1":"s2_v1",
                       "s2_f2" : "s2_v2",
                       "s2_f3" : {
                                    "s3_f1":"s3_v1"
                                 }
                     }
              }
}

swagger_template = { "d0" : 
                     {
                       "d1_f1":"d1_v1",
                       "d3_f1" :"d3_v1"
                     }
            }

mapping = {
            "d1_f1":"s1_f1",
            "d3_f1" : "s3_f1"
          }

def find_mapping_key(v):  
      return (mapping[v])


def find_input_value(k,input_json):  
  if k in input_json:
        return input_json[k]
  for v in input_json.values():
        if isinstance(v, dict):
            return find_input_value(k,v)
  return None



def transform(swagger_template):  
  for k, v in swagger_template.items():   
    if isinstance(v, dict):
      transform(v)      
    else:
         print("{0} : {1}".format(k, v))
         #find the mapping value for this key in mapping JSON 
         print(find_mapping_key(k))
         mapping_key=find_mapping_key(k)
         #find the value for that mapping key in input_json 
         print(find_input_value(mapping_key,input_json))




transform(swagger_template)

its giving correct value for one mapping but for another one its returned NONE .

enter image description here



from update nested dictionary values from another nested dictionary based on mapping provided in dictionary

No comments:

Post a Comment