三目運算符
a = raw_input("請輸入a的值:") b = raw_input("請輸入b的值:") result = 1 if a > b else 0 print result
尋找差別
# 數據庫中原有 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 } } # cmdb 新彙報的數據 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 } } 須要刪除:? 須要新建:? 須要更新:?
c1 = "abc" c2 = 'xyz' 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 } } print "========數據庫中原有old_dict=============" for item in old_dict: print item,old_dict[item] s_old = set(old_dict.keys()) s_new = set(new_dict.keys()) print s_old,s_new #將對鍵值轉化爲集合後,進行對比,刪除多餘的 #difference : A中存在,B中不存在 dif = s_old.difference(s_new) print "old_dict中須要刪除",dif old_dict.pop(dif.pop()) print "========刪除old_dict=============" for item in old_dict: print item,old_dict[item] #對比字典中的每一項值 for item in new_dict: #print item key = item n = new_dict[item] o = old_dict.get(key) #print (n,d) # 判斷新鍵是否存在於老數據庫表中 if o != None: for item in n: #print item, n[item] #print item, o[item] if n[item] == o[item]: #print "值同樣,不用更新" pass else: #print "值不同,要更新" o[item] = n[item] else: old_dict[item] = n print "=========新彙報的數據============" for item in new_dict: print item,new_dict[item] print "========更新後的old_dict=============" for item in old_dict: print item,old_dict[item]