练习-python集合set

 1 #寻找差异
 2 #要求:原来没有的,新加入;原来有的,更新;新的没有,原来的有,删除原来的
 3 #无需考虑内部元素改变
 4 #数据库中原有
 5 old_dict = {
 6     "#1":{ "hostname":"c1", "cpu_count": 2, "mem_capicity": 80 },
 7     "#2":{ "hostname":"c1", "cpu_count": 2, "mem_capicity": 80 },
 8     "#3":{ "hostname":"c1", "cpu_count": 2, "mem_capicity": 80 }
 9 }
10 
11 #cmdb 新汇报的数据
12 new_dict = {
13     "#1":{ "hostname":"c1", "cpu_count": 2, "mem_capicity": 800 },
14     "#3":{ "hostname":"c1", "cpu_count": 2, "mem_capicity": 80 },
15     "#4":{ "hostname":"c2", "cpu_count": 2, "mem_capicity": 80 }
16 }
17 
18 old = set(old_dict.keys())
19 new = set(new_dict.keys())
20 update_set = old.intersection(new)    #交集,输出更新的数据
21 delete_set = old.symmetric_difference(update_set)   #差集,新的没有,旧的有的,删除
22 add_set = new.symmetric_difference(update_set)     #差集,新的有,旧的没有,添加
23 print(update_set)
24 print(delete_set)
25 print(add_set)
26 old_dict.pop("#2")
27 old_dict.update(new_dict)
28 print(old_dict)

#执行结果:

{'#1', '#3'}
{'#2'}
{'#4'}
{'#4': {'mem_capicity': 80, 'hostname': 'c2', 'cpu_count': 2}, '#3': {'mem_capicity': 80, 'hostname': 'c1', 'cpu_count': 2}, '#1': {'mem_capicity': 800, 'hostname': 'c1', 'cpu_count': 2}}

 

转载于:https://www.cnblogs.com/repo/p/5421600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值