You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo场景下不使用第三方库对比Python字典并获取差异

不依赖第三方库对比字典并返回差异的实现方法

针对你在Odoo开发中需要对比两个字典、提取list2相对list1新增内容的需求,这里提供纯Python原生实现的方法,无需任何第三方库:

def get_dict_difference(dict1, dict2):
    differences = {}
    # 遍历目标字典的所有分类及对应条目
    for category, items in dict2.items():
        # 如果分类在dict1中不存在,直接将整个分类加入差异
        if category not in dict1:
            differences[category] = items.copy()
            continue
        # 将dict1中该分类的条目转换为可哈希的元组集合,用于快速查找
        existing_item_tuples = set(
            tuple(sorted(item.items())) for item in dict1[category]
        )
        # 筛选dict2中不在dict1里的新增条目
        new_items = [
            item for item in items
            if tuple(sorted(item.items())) not in existing_item_tuples
        ]
        # 有新增条目时才加入差异字典
        if new_items:
            differences[category] = new_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_difference(list1, list2)
import pprint
pprint.pprint(differences)

代码说明

  1. 遍历目标字典:以list2为基准遍历所有分类和条目,聚焦提取list2相对list1的新增内容。
  2. 处理新增分类:若list2的分类在list1中不存在,直接将该分类的全部条目加入差异字典。
  3. 条目去重对比:因字典不可哈希,将每个条目转换为排序后的键值对元组(消除键顺序对内容判断的影响),存入集合实现快速查找。
  4. 筛选新增条目:遍历list2的条目,筛选出list1中没有的内容,仅当有结果时才加入差异字典,避免空分类占用空间。

运行代码后,输出结果将完全匹配你期望的差异字典格式。

内容的提问来源于stack exchange,提问作者Arthur Fortin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:53:21