Python练习三

三目运算符
a = raw_input("请输入a的值:")
b = raw_input("请输入b的值:")
result = 1 if a > b else 0
print result
View Code
寻找差异
# 数据库中原有
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]
View Code


原文地址:https://www.cnblogs.com/jessie-ji/p/6501556.html