两段请求报文,判断不一样的key和value,只判断d2里和d1不同的值,和全部不同的key
ok_req={
"version": "9.0.0",
"is_test": True,
"store": "",
"urs": "",
"device": {
"os": "android",
"imei": "99001062198893",
"device_id": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"mac": "02:00:00:00:00:00",
"galaxy_tag": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"udid": "a34b1f67dd5797df93fdd8b072f1fb8110fd0db6",
"network_status": "wifi"
},
"adunit": {
"category": "VIDEO",
"location": "1",
"app": "7A16FBB6",
"blacklist": ""
},
"ext_param":{
"is_start" : 0,
"vId":"VW0BRMTEV"
}
}
not_ok={
"version": "9.0.0",
"is_test": True,
"urs": "1",
"store": "",
"device": {
"os": "android",
"imei": "99001062298893",
"device_id": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"mac": "02:00:00:00:00:00",
"galaxy_tag": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"udid": "a34b1f67dd5797da93fdd8b072f1fb8110fd0db6",
"network_status": "wifi"
},
"adunit": {
"category": "VIDEO",
"location": "1",
"app": "7A16FBB6",
"blacklist": ""
},
"ext_param": {
"is_start": 0,
"vid": "VW0BRMTEV"
}
}
方法一的需求分析:
1. 循环d1的key,通过key去d2里取值,取不到的就是d2中不存在这个key,d2与d1里不一样的key
2. 判断通过key取值的类型,如果是dict类型的继续循环
3. 把d1和d2中的key转换成集合类型,取差集,取出的key即d1和d2中不一样的key
def compare(dic_1,dic_2):
for k in dic_1:
v1=dic_1.get(k)
v2=dic_2.get(k,‘get不到值‘)#通过k去d2里取值,d2里如果没有这个key,返回get不到值
if type(v1)==dict:
compare(v1,v2)#取值为dict类型递归
else:
if v1 != v2 and v2 !=‘get不到值‘ :
print (‘value不一样的:key是%s,v1是%s,v2是%s‘%(k,v1,v2))
r1 = set(dic_1.keys())
r2 = set(dic_2.keys())
res=r1.symmetric_difference(r2)
print(‘两个请求报文中不一样的key是:‘,‘,‘.join(res))
compare(ok_req,not_ok)
方法二的需求分析:
1. 已知报文是二维,创建一个方法,把二维字典变成一维字典,key用特定的符号连接起来
2. 循环d1的key,取d2里面取值,如果v1==v2,就在d2里把这个键值对删除,不同的话,说明key是d1里与d2里k-v不同的数据
3. d2里剩下的全是和d1里k-v不同的数据,循环d2剩余的数据并输出
def buildDict(dict_0):#把报文的二维字典变成一维,二维字典的样式变成{一维字典key||二维key:value}
dict_t = {}
for key in dict_0:
value = dict_0.get(key)
if type(value) == dict:
for k,v in value.items():
dict_t[key+‘||‘+k]=v
else:
dict_t[key]=value
return dict_t
def compare(ok_req,not_ok):
dic_1 = buildDict(ok_req)#把ok_req报文变成一维的字典格式
dic_2 = buildDict(not_ok)#把not_ok报文变成一维的字典格式
for k in dic_1:
v1 = dic_1.get(k)
v2 = dic_2.get(k)
if v1==v2:
dic_2.pop(k)#把dict_2中key和value与dict_1中一样的删除
else:
print(‘dic_1中数据不同的k-v,是‘ + k+‘:‘+dic_1.get(k))
for k in dic_2:#dic_2中剩余的都是和dic_1中不一样的key
print(‘dic_2中不一样的k-v,是‘+k+‘:‘+dic_2.get(k))
compare(ok_req,not_ok)