python中2个字典比较
用到的两个函数:
set() 函数:创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
cmp(x,y) 函数:用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
1.列出不同的键值
#!/usr/bin/python # -*- coding:utf-8 -*- import os, sysimport re reload(sys) sys.setdefaultencoding("utf8") dct0 = {"name":"zhang","age":"23"} dct1 = {"name":"san","age":"23"} def cmpdicts(dct0, dct1): diffs = set() keys = set(dct0.keys() + dct1.keys()) for k in keys: if cmp(dct0.get(k), dct1.get(k)): diffs.add(k) return diffs dict_diff = cmpdicts(dct0, dct1) print "字典不同的值:" print dict_diff
运行结果:
字典不同的值: set(['name'])
2.列出所有的不同键值
#!/usr/bin/python # -*- coding:utf-8 -*- import os, sys import re reload(sys) sys.setdefaultencoding("utf8") dct0 = {"name":"zhang","age":"23"} dct1 = {"name":"san","age":"23","sex":"1"} print "字典dct0的值:" + str(dct0) print "字典dct1的值:" + str(dct1) differ = set(dct0.items()) ^ set(dct1.items()) print "字典不同的值:" print(differ) print "查看字典dct0和字典dct1共有的key" print set(dct0.keys()) & set(dct1.keys()) print "查看字典dct0和字典dct1不共有的key" print set(dct0.keys()) ^ set(dct1.keys()) print "查看在字典dct1里面而不在字典dct0里面的key:" print set(dct1.keys()) - set(dct0.keys()) print "查看字典dct0和字典dct1相同的键值对:" print set(dct0.items()) & set(dct1.items())
运行结果:
字典dct0的值:{'age': '23', 'name': 'zhang'} 字典dct1的值:{'age': '23', 'name': 'san', 'sex': '1'} 字典不同的值: set([('name', 'zhang'), ('sex', '1'), ('name', 'san')]) 查看字典dct0和字典dct1共有的key set(['age', 'name']) 查看字典dct0和字典dct1不共有的key set(['sex']) 查看在字典dct1里面而不在字典dct0里面的key: set(['sex']) 查看字典dct0和字典dct1相同的键值对: set([('age', '23')])
天下难事,必作于易;天下大事,必作于细