Skip to main content
 首页 » 编程设计

python之如何在 python 中合并附加两个嵌套字典

2025年05月04日16tintown

例如我有两个字典:

schema = { 
    'type': 'object', 
    'properties': { 
        'reseller_name': { 
            'type': 'string', 
        }, 
        'timestamp': { 
            'type': 'integer', 
        }, 
    }, 
    'required': ['reseller_name', 'timestamp'], 
} 

和

schema_add = { 
    'properties': { 
        'user_login': { 
            'type': 'string', 
        }, 
    }, 
    'required': ['user_login'], 
} 

如何将 next 与附加结果字典合并:

schema_result = { 
    'type': 'object', 
    'properties': { 
        'reseller_name': { 
            'type': 'string', 
        }, 
        'timestamp': { 
            'type': 'integer', 
        }, 
        'user_login': { 
            'type': 'string', 
        }, 
    }, 
    'required': ['reseller_name', 'timestamp', 'user_login'], 
} 

规则:

在示例中,properties 和 required 与 scheme 和 scheme_add 的路径相同。

  1. 如果两个dict都有相同路径的dict,则它们按照相同的规则合并。
  2. 如果两个字典都有相同路径的列表,则将第一个列表与第二个列表相加。
  3. 如果两个字典都具有具有相同路径的简单值(或字典和非字典或列表和非列表),则第一个值将被第二个值覆盖。
  4. 如果只有一个字典有某个路径的键,而不是设置这个键和值。

请您参考如下方法:

不确定问题在哪里,但你写下来的方式几乎就像一个计算机程序,这个例子就像一个测试用例。为什么不从这里开始呢?

def add_dict(d1, d2): 
    newdict = {} 
    for (key, value) in d1.iteritems(): 
        if key in d2: ... 
            #apply rules, add to newdict, use  
        else: 
            #simply add 
    for (key, value) in d2.iteritems(): 
        if not key in d1: 
            # simply add 
    return newdict 

这可能会写得更紧凑,但可能更容易编辑。

编辑..写完最后一条评论后,忍不住写了一个更好的实现

def merge_values(a,b): 
    if a==None or b==None: 
        return a or b 
    # now handle cases where both have values 
    if type(a)==dict: 
        return add_dict(a, b) 
    if type(a)==list: 
        ... 
 
def add_dict(d1,d2): 
    return dict( 
        [ 
            (key, 
             merge_values( 
                 d1.get(key,None), 
                 d2.get(key,None))) 
            for key 
            in set(d1.keys()).union(d2.keys()) 
        ])