简体   繁体   中英

update in nested dictionary from another dictionary key value pair

I am trying to update an existing nested dictionary from another dictionary which contains key-value pairs, updating should be done based on key. If a key exists in another dictionary then it should be updated, and otherwise left as it is.

Here's the recursive code I am trying to update the dictionary.

    def update_swagger(d, u):
        for k, v in u.items():
            if isinstance(v, collections.Mapping):
                d[k] = update_swagger(d.get(k, {}), v)
            else:
                d[k] = v
        return d

Input dictionary in this as a parameter as follows:

    swagger_template = { 
                          "d0" : 
                         {
                           "d0_f1":"d0_v1",
                           "d3_f1" :"d3_v1"
                         },
                         "d1" : 
                         {
                           "d1_f1":"d1_v1",
                           "d1_f2" :"d1_v2"
                         }
                }

and the dictionary which I am passing for updating is as follows:

    {'d0_f1': 's1_v1', 
     'd3_f1': 's3_v1', 
     'd1_f1': 's2_v1', 
     'd1_f2': 's2_v2'}

The result from the existing code I am getting is:

    {'d0': 
        {'d0_f1': 'd0_v1', 
         'd3_f1': 'd3_v1'}, 
     'd1': 
        {'d1_f1': 'd1_v1', 
         'd1_f2': 'd1_v2'}, 
     'd0_f1': 's1_v1', 
     'd3_f1': 's3_v1', 
     'd1_f1': 's2_v1', 
     'd1_f2': 's2_v2'
    }
def update_swagger1(d, u):
    for k, v in d.items():        
        if isinstance(v, collections.Mapping):            
            for v1, v2 in v.items():
                if v1 in u.keys():
                    d[k][v1] = u[v1]                                  
    return d

update_swagger1(d,u)
{'d0': {'d0_f1': 's1_v1', 'd3_f1': 's3_v1'},
 'd1': {'d1_f1': 's2_v1', 'd1_f2': 's2_v2'}}

Another way to do it could be:

def update_swagger(d, u):
    k,v = u
    if type(d) == type({}):
        if k in d:
            d[k] = v
        else:
            [ update_swagger(d_i,u) for d_i in d.values() ]

And then:

for item in new_data.items():
    update_swagger(swagger_template,item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM