您的位置:首页 > 其它

字典对比:字典式元素组成的列表进行对比,如同键,值相减

2020-06-07 05:50 106 查看

数据格式:
数据类型为列表,列表的索引元素为字典。由字典组织的列表。

分析:
1、遍历字典同键,再根据同键得出相应的值。
2、值相减形成新的字典,重新定义字典,或跟新现有字典。

##对比CRC值,格式和实例如下:Compare_Dict_List(Old_CRC_Dict,New_CRC_Dict),返回值的形式同样。
#Old_CRC_Dict = [{'10GE1/0/10':"60"},{'10GE1/0/11':"20"},{'10GE1/0/12':"80"}]
#New_CRC_Dict = [{'10GE1/0/10':"70"},{'10GE1/0/11':"40"},{'10GE1/0/12':"20"}]

脚本内容如下:

def Compare_Dict(Old_CRC_DictList,New_CRC_DictList):
Temp_List=[]
for x in range(len(Old_CRC_DictList)):
#print (Old_CRC_DictList[x])
for y in range(len(New_CRC_DictList)):
#print (New_CRC_DictList[y])
Temp_Dict = {}
for k1,v1 in New_CRC_DictList[y].items():
#print (k1)
#print (Old_CRC_DictList[x][k1])
if Old_CRC_DictList[x].get(k1):
Temp_Dict[k1] = int(v1)-int(Old_CRC_DictList[x][k1])
#if int(Old_CRC_DictList[x][k1])-int(v1) < 10:
#    print ("True")
print (Temp_Dict)
Temp_List.append(Temp_Dict)
print (Temp_List)
return Temp_List

优化之后的脚本:

def Compare_DictList(Old_CRC_DictList,New_CRC_DictList):
Temp_List=[]
for x,y in zip(Old_CRC_DictList,New_CRC_DictList):
Temp_Dict = {}
for k1,v1 in y.items():
if x.get(k1):
Temp_Dict[k1] = int(v1)-int(x[k1])
#if int(x[k1])-int(v1) < 10:
#    print ("True")
#print (Temp_Dict)
Temp_List.append(Temp_Dict)
print (Temp_List)
return Temp_List
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: