Home > Net >  how to get difference of added datas between python dictionary?
how to get difference of added datas between python dictionary?

Time:05-18

Assuming,

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

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

as i know, taking up 'deepdiif' isn't right because it has to have same architecture of Dictionary how can i get that diffrence of added datas of Dictionary in simple and easy way?

CodePudding user response:

You can do this with set.symmetric_difference():

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

If you have more dictionary keys than just one (but both have the same key set):

>>> 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]}

EDIT: if you don't know a priori that the two dictionaries have the same key set, you can make this a little bit more robust by treating it as a "differentiated union" where keys in the intersection of the two key sets are diff'd, and keys not in the intersection are treated as a normal 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

Output:

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