set集合

小练习

下列两个字典,使用set得出需要修改(交集)、需要删除(差集)、需要添加的内容。

old_dict = {
    "#1":{'hostname':'c1', 'cpu': 2, 'dimm':2048},
    "#2":{'hostname':'c2', 'cpu': 2, 'dimm':2048},
    "#3":{'hostname':'c3', 'cpu': 2, 'dimm':2048},
}

new_dict = {
    "#1":{'hostname':'c1', 'cpu': 2, 'dimm':4096},
    "#3":{'hostname':'c3', 'cpu': 2, 'dimm':2048},
    "#4":{'hostname':'c4', 'cpu': 2, 'dimm':2048},
}

#只对keys作比较,得到所有keys的列表,并转为set集合
old_list = set(old_dict.keys())
new_list = set(new_dict.keys())

#需要更新的内容(交集)
update_set  = old_list .intersection(new_list)

#需要删除的内容(差集)
delete_set = old_list.difference(update_set)

#需要添加的内容
add_set = new_list.difference(update_set)

print(update_set)
print(delete_set)
print(add_set)

运行结果:

{'#1', '#3'}
{'#2'}
{'#4'}

图解:

 

set中difference和symmetric_difference的区别

例:

s1 = set([11,22,33])
s2 = set([33,44])
ret1 = s1.difference(s2)
ret2 = s1.symmetric_difference(s2)
print(ret1)
print(ret2)

运行结果:

{11, 22}
{11, 44, 22}

说明:

ret1中只循环s1
ret2中先循环s1,然后循环s2

 

posted @ 2017-12-27 14:51  jacky_zhao  阅读(103)  评论(0编辑  收藏  举报