python集合set

 set 交集、差集

在新旧字典中,新旧字典均存在的KEY进行更新。旧字典存在而新字典不存在,则删除。旧字典不存在而新字典存在的KEY,则新增;

 1 old_dict = {
 2     "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 3     "#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 4     "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}
 5 }
 6 new_dict = {
 7     "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 8     "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
 9     "#4": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}
10 }
11 # 转换成set集合
12 old = set(old_dict)
13 new = set(new_dict)
14 
15 # 交集
16 update_set = new.intersection(old)
17 
18 # 差集(只拿old
ew对象与update_set对象进行比较取得差集)
19 # delete_set = old.difference(update_set)
20 # add_set = new.difference(update_set)
21 
22 # 对称差(双向进行对比最终得到差集)
23 delete_set = old.symmetric_difference(update_set)
24 add_set = new.symmetric_difference(update_set)
25 
26 print update_set
27 print delete_set
28 print add_set
# 执行结果
set(['#3', '#1']) set(['#2']) set(['#4'])
原文地址:https://www.cnblogs.com/mjoy/p/5773466.html