python 对比两个字典的差异

  • 分类: Python
  • 发表日期:2021-10-25 11:27:00
  • 最后修改:2021-10-25 11:27:00

 找出两个字典的差异:

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

 

转载于: python 对比两个字典的差异 - 番茄土豆西红柿 - 博客园 (cnblogs.com)

 

post
2021年7月9日 09:40 原创 草稿

针对情报平台的多种 es dsl 测试

post
2021年7月13日 09:36 原创
post
2021年7月30日 12:01 原创
post
2021年7月30日 12:15 原创
post
2021年7月30日 15:07 原创
post
2021年7月30日 15:13 原创
post
2021年7月30日 15:18 原创
post
2021年7月30日 15:24 原创
post
2021年7月30日 16:09 原创
post
2021年7月30日 16:02 原创
post
2021年8月16日 15:28 原创
post
2021年8月16日 20:01
post
2021年8月17日 12:07 原创
post
2021年8月31日 15:42 原创
post
2021年10月8日 16:17
post
2021年10月13日 11:43
post
2021年10月21日 15:47 原创

0 评论

大哥整点话呗~