简体   繁体   English

从另一个字典键值对更新嵌套字典

[英]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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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