【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)}
print('---------')
# 共有的key
diff = dict1.keys() & dict2
print(diff)
print('-------------------')
# 相同key,不同value
diff_vals = [(k, dict1[k], dict2[k]) for k in diff if dict1[k] != dict2[k]]
print(diff_vals)  # [('c', 3, 5)]
print('-----------')
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', 'w'}
# 查看在字典a里面而不在字典b里面的key
print(a.keys() - b.keys())  # {'y'}
# 查看字典a和字典b相同的键值对
print(a.items() & b.items()) # {('x', 1)}

 

总结:相同  &,不同 ^,在(被减数) -不在(减数)

 

参考:https://www.cnblogs.com/robinunix/p/10919783.html

上一篇:《Python基础知识——组合数据类型之字典》


下一篇:字典与集合