您现在的位置是:网站首页 > 博客日记 >

python对比两个字典差异

作者:YXN-python 阅读量:7 发布日期:2023-10-30

def diff_dicts(dict1, dict2):
    """
    比较两个字典的差异
    :param dict1: 原始字典
    :param dict2: 对比字典
    :return: 字典的增删改差异字典(注意:修改返回的对比字典中的值)
    """
    insertions = []
    updates = []
    deletions = []

    # 插入、更新
    for key, value in dict2.items():
        if key not in dict1:
            insertions.append({key: value})
        elif dict1[key] != value:
            updates.append({key: value})

    # 删除
    for key, value in dict1.items():
        if key not in dict2:
            deletions.append({key: value})

    return {
        'insert': insertions,
        'update': updates,
        'delete': deletions
    }


dict1 = {'a': 1, 'b': {'c': 3}, 'c': 3}
dict2 = {'a': 2, 'b': {'c': 6}, 'd': 4}

result = diff_dicts(dict1, dict2)
print(result)

# 输出:{'insert': [{'d': 4}], 'update': [{'a': 2}, {'b': 3}], 'delete': [{'c': 3}]}

YXN-python

2023-10-30