Python之字典列表的转换及for循环的方法

高洛峰
发布: 2017-03-10 18:46:55
原创
1533 人浏览过

寻找差异

# 原有dict
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 }
}
  
需要删除:?
需要新建:?
需要更新:?
登录后复制

代码:

#-*-coding:utf-8-*-
# 原有数据

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 }
}
  
old_set = set(old_dict.keys())
update_list = list(old_set.intersection(new_dict.keys()))
for i in update_list:
     if cmp(old_dict[i],new_dict[i]) != 0:
         update_list.remove(i)
       
#print update_list
 
 
new_list = []
del_list = []
 
for i in new_dict.keys():
    if i not in update_list:
        new_list.append(i)
for i in old_dict.keys():
    if i not in update_list:
        del_list.append(i)
 
print update_list
print new_list
print del_list
运行结果:
['#3']
['#1', '#4']
['#2', '#1']
 
 
本节使用了字典与列表的转换,列表移除某个值,for循环,cmp内置函数,if判断
登录后复制


以上是Python之字典列表的转换及for循环的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!