zoukankan      html  css  js  c++  java
  • 练习-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}}

  • 相关阅读:
    day30---内置函数
    day30---绑定方法与非绑定方法
    元类以及属性查找
    python 内置方法/魔法方法
    python 面向对象高级-反射机制
    centos7下jenkins升级
    屏蔽百度右侧热搜
    centos7部署汉化版gitlab
    CentOS 7 安装 Jenkins
    centos7安装与配置ansible
  • 原文地址:https://www.cnblogs.com/repo/p/5421600.html
Copyright © 2011-2022 走看看