本文介绍一种不依赖第三方库的原生 Python 方法,用于比较两个结构相似的嵌套字典(键为字符串、值为字典列表),精准提取 list2 中存在但 list1 中缺失的键值对,适用于 Odoo 等场景下的数据变更检测。
本文介绍一种不依赖第三方库的原生 python 方法,用于比较两个结构相似的嵌套字典(键为字符串、值为字典列表),精准提取 `list2` 中存在但 `list1` 中缺失的键值对,适用于 odoo 等场景下的数据变更检测。
在实际开发(如 Odoo 模块定制)中,常需对比前后状态的数据结构以识别新增或变更项。当数据以“分类 → 商品列表”形式组织(即字典的值为字典列表)时,标准的 == 或 dict.items() 对比无法满足细粒度差异识别需求——我们需要的是语义级差异:哪些分类是新增的?哪些分类下新增了哪些具体条目?
以下是一个简洁、健壮且无需外部依赖的实现方案:
def get_dict_differences(list1, list2): """ 比较两个嵌套字典,返回 list2 中存在但 list1 中缺失的全部条目。 支持新增分类(key)与分类内新增条目(字典项)两种差异。 """ differences = {} for key, value in list2.items(): if key not in list1: # CASE I: list2 有而 list1 没有的分类 → 整个列表视为差异 differences[key] = value.copy() else: # CASE II: 分类共有的情况下,逐项比对列表中的字典 diff_items = [] for item in value: # 注意:此处依赖字典的相等性判断(Python 默认按内容深比较) if item not in list1[key]: diff_items.append(item) if diff_items: differences[key] = diff_items return differences# 示例数据list1 = { 'Office Furniture': [ {'name': 'Office chairs can harm your floor: protect it.', 'qty': 3} ]}list2 = { 'Office Furniture': [ {'name': 'Office chairs can harm your floor: protect it.', 'qty': 3}, {'name': '160x80cm, with large legs.', 'qty': 1} ], 'Services': [ {'name': 'designing', 'qty': 1} ]}# 执行差异计算differences = get_dict_differences(list1, list2)print(differences)# 输出:# {# 'Office Furniture': [{'name': '160x80cm, with large legs.', 'qty': 1}],# 'Services': [{'name': 'designing', 'qty': 1}]# }
✅ 关键说明与注意事项:
该方法轻量、透明、易调试,完美契合 Odoo 等框架中对业务数据变更的轻量级追踪需求。
立即学习“Python免费学习笔记(深入)”;