主要用到的set里的功能
# 数据库中原有
old_dict = {
"#1": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
"#2": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
"#3": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80}
}
# cmdb 新汇报的数据
new_dict = {
"#1": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 800},
"#3": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
"#4": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 80}
}
要求得到三个列表:
要更新的数据
要删除的数据列表
要添加的数据列表
old_dict = {
"#1":{ 'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#2":{ 'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#3":{ 'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}
new_dict = {
"#1":{ 'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800 },
"#3":{ 'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80 },
"#4":{ 'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80 }
}
# print(old_dict)
# print(new_dict)
updatelist = [] #要更新的数据列表
dellist = [] #要删除的数据列表
addlist = [] #要添加的数据列表
oldset = set(old_dict.keys()) #将old_dic赋值给oldset
newset = set(new_dict.keys())
dellist = oldset.difference(new_dict.keys()) #旧的有,新的没有,表示要删除的数据
print(dellist)
addlist = newset.difference(old_dict.keys()) #新的有,就的没有,表示要添加的数据
print(addlist)
for i in new_dict.keys():
if i in old_dict.keys():
oldhard = set(old_dict[i].values())
newhard = set(new_dict[i].values())
if oldhard.issubset(newhard): #比较两个set是否一样。
pass
else:
updatelist = [i]
print(dellist,addlist,updatelist)
本文介绍了一种通过对比两个字典来找出需要更新、删除和添加的条目方法。使用Python set集合操作来高效地确定数据变化,适用于配置管理或资产库存同步场景。
1334

被折叠的 条评论
为什么被折叠?



