本文介绍python字典嵌套的一个实例。
/tmp/test
sdfd.dfdf-dfdfd ok=0 changed=21 unreachable=0 failed=0 sdfd.dnvjrendddfdf-dfdfd ok=10 changed=1 unreachable=1 failed=0 sfejifdfd.dfdf-dfdfd ok=5 changed=10 unreachable=0 failed=1 dfjdfk jdfkd dfdjfdkf dfdfjdfjd jdkfjdk aaaaa dfjifjk k kkkkkk kkkkkkkk kkkkkk kkkkk
multiple_dictionary.py
#!/usr/bin/env python import os import sys import re dic = dict() dic_sub = dict() fp = open("/tmp/test", "r") for line in fp : ret = re.match("(.*) *(ok=\d+).+(changed=\d+).*(unreachable=\d+).*(failed=\d+)",line) if ret : #print ret.group(1) #print ret.group(2) #print ret.group(3) #print ret.group(4) #print ret.group(5) for i in range(2,6): key = ret.group(i).split("=")[0] value = ret.group(i).split("=")[1] dic_sub[key] = value dic[ret.group(1)] = {} dic[ret.group(1)].update(dic_sub) else : continue for key in dic.keys() : if dic[key]['unreachable'] == '0' and dic[key]['failed'] == '0' : print "SUCCESS:", key elif dic[key]['unreachable'] != '0' : print "FAILED-UNREACHABLE:", key elif dic[key]['failed'] != '0' : print "FAILED-ERROR:", key
结果:
sdfd.dfdf-dfdfd unreachable 0 changed 21 ok 0 failed 0 sfejifdfd.dfdf-dfdfd unreachable 0 changed 10 ok 5 failed 1 sdfd.dnvjrendddfdf-dfdfd unreachable 1 changed 1 ok 10 failed 0 SUCCESS: sdfd.dfdf-dfdfd FAILED-ERROR: sfejifdfd.dfdf-dfdfd FAILED-UNREACHABLE: sdfd.dnvjrendddfdf-dfdfd