ホームページ  >  記事  >  バックエンド開発  >  Python辞書リスト変換とforループ方式

Python辞書リスト変換とforループ方式

高洛峰
高洛峰オリジナル
2017-03-10 18:46:551536ブラウズ

間違い探し

# 原有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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。