如何获得 python 词典之间添加数据的差异?

how to get difference of added datas between python dictionary?

假设,

dict1 = { "A" : ["a","b","c"]} # old one
dict2 = { "A" : ["a","b","c","d"]} # new one

#i wanna get
dict3 = {"A":["d"]}

据我所知,使用 'deepdiif' 是不对的,因为它必须具有与 Dictionary 相同的架构 我怎样才能以简单易行的方式获得词典添加数据的差异?

你可以用 set.symmetric_difference():

set(*dict1.values()).symmetric_difference(*dict2.values())

如果您的字典键多于一个 (但两者具有相同的键集):

>>> dict1
{'A': ['a', 'b', 'c'], 'B': [1, 2, 3, 4]}

>>> dict2
{'A': ['a', 'b', 'c', 'd'], 'B': [4, 3, 2]}

>>> {k: list(set(dict1[k]).symmetric_difference(dict2[k])) for k in dict1}
{'A': ['d'], 'B': [1]}

编辑:如果您不知道 先验 这两个词典具有相同的键集,您可以通过将其视为“ differentiated union”,其中两个键集的交集中的键是不同的,不在交集中的键被视为正常 dict.union:

def differentiated_union(d1, d2):
    result = {}
    for key in set(d1).union(d2):
        d1_vals = d1.get(key, set())
        d2_vals = d2.get(key, set())
        result[key] = list(set(d1_vals).symmetric_difference(d2_vals))
    return result

输出:

>>> differentiated_union(dict1, dict2)
{'A': ['d'], 'B': [1], 'C': ['z', 'x', 'y'], 'D': ['p', 'q', 'r']}