python 对比两个字典的差异
实际遇到的问题逻辑很繁杂,就不全写了。最后是通过对比两个字典差异来解决的。找出两个字典的差异,可参考以下代码。
dict1 = {'a':1,'b':2,'c':3,'d':4} dict2 = {'a':1,'b':2,'c':5,'e':6} differ = set(dict1.items()) ^ set(dict2.items()) print(differ) #所有差异 #输出:{('c', 3), ('e', 6), ('c', 5), ('d', 4)} diff = dict1.keys() & dict2 diff_vals = [(k, dict1[k], dict2[k]) for k in diff if dict1[k] != dict2[k]] print(diff_vals) #相同key,不同value #输出:[('c', 3, 5)]
其他参考:
a = { "x":1, "y":2, "z":3 } b = { "x":1, "w":11, "z":12 } print(a.items()) >>>dict_items([('x', 1), ('y', 2), ('z', 3)]) # 查看两个字典共有的key print(a.keys() & b.keys()) >>>{'x', 'z'} # 查看字典a 和字典b 的不共有的key print(a.keys() ^ b.keys()) >>>{'y'} # 查看在字典a里面而不在字典b里面的key print(a.keys() - b.keys()) >>>{('x', 1)} # 查看字典a和字典b相同的键值对 print(a.items() & b.items()) >>>{'w', 'y'}
做有积累的事~~