zoukankan      html  css  js  c++  java
  • python—打印字典 ,collection模块中Orderedict用法,字典与文件

    一. python 中,如果字典里面又有字典,则输出不好看。

    方法一:使用内置的pprint
    方法二:自己写一个函数

    method 1:

    Python代码


    >>> d = {1:{'who':{'name':'Michael','age':20,'job':{'P':'90-91','G':'91-93'}}},2:{'who':{'name':'Mary','age':18,'job':{'P':'90-93','G':'93-95'}}}} >>> d {1: {'who': {'job': {'P': '90-91', 'G': '91-93'}, 'age': 20, 'name': 'Michael'}}, 2: {'who': {'job': {'P': '90-93', 'G': '93-95'}, 'age': 18, 'name': 'Mary'}}} >>> import pprint >>> pprint.pprint(d) {1: {'who': {'age': 20, 'job': {'G': '91-93', 'P': '90-91'}, 'name': 'Michael'}}, 2: {'who': {'age': 18, 'job': {'G': '93-95', 'P': '90-93'}, 'name': 'Mary'}}}

     

    method 2:
    Python代码

    >>> d = {1:{'who':{'name':'Michael','age':20,'job':{'P':'90-91','G':'91-93'}}},2:{'who':{'name':'Mary','age':18,'job':{'P':'90-93','G':'93-95'}}}}  
    >>> d  
    {1: {'who': {'job': {'P': '90-91', 'G': '91-93'}, 'age': 20, 'name': 'Michael'}}, 2: {'who': {'job': {'P': '90-93', 'G': '93-95'}, 'age': 18, 'name': 'Mary'}}}  
      
    >>> def print_dict (d,n=0):  
        for k,v in d.items():  
            print '	'*n,  
            if type(v)==type({}):  
            print "%s : {" % k  
                print_dict(v,n+1)  
            else:  
                print("%s : %s" % (k,v))  
        if n!=0:  
            print '	'*(n-1)+ '}'  
      
              
    >>> print_dict(d)  
     1 : {  
        who : {  
            job : {  
                P : 90-91  
                G : 91-93  
            }  
            age : 20  
            name : Michael  
        }  
    }  
     2 : {  
        who : {  
            job : {  
                P : 90-93  
                G : 93-95  
            }  
            age : 18  
            name : Mary  
        }  
    }  
    

      

    二.Orderedict

    orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

    注意:字典默认循环只输出key

    复制代码
    import collections
    dic = collections.OrderedDict()
    dic["k1"] = "v1"
    dic["k2"] = "v2"
    dic["k3"] = "v3"
    print(dic)
    #实现原理:相当于用列表(有序)来维护字典(无序)排序,以下仅供理解
    # dic = {"k1":"v1","k2":"v2"}
    # li = ["k1","k2"]
    # for i in li:
    #     print(dic.get(i))
    
    执行结果:无论执行多少次结果一样
    OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
    

      

    def popitem(self, last=True):
    

     

    #有序删除和指定删除
    import collections
    dic = collections.OrderedDict()
    dic["k1"] = "v1"
    dic["k2"] = "v2"
    dic["k3"] = "v3"
    print(dic)
    dic.popitem()    #有序拿掉,每次拿掉最后一个,相当于内存的栈存放,后进先出原则,而pop()就是强制拿出指定的值
    print(dic)
     
     执行结果:
    OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
    OrderedDict([('k1', 'v1'), ('k2', 'v2')])
    

      

    def move_to_end(self, key, last=True):
    

      

    #把指定键值移到最后
    import collections
    dic = collections.OrderedDict()
    dic["k1"] = "v1"
    dic["k2"] = "v2"
    dic["k3"] = "v3"
    print(dic)
    dic.move_to_end("k1")    #把指定键值移到最后
    print(dic)
     
    #执行结果:
    OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
    OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
    

      

    def setdefault(self, key, default=None):
    

     

    #添加默认键
    import collections
    dic = collections.OrderedDict()
    dic["k1"] = "v1"
    dic["k2"] = "v2"
    dic["k3"] = "v3"
    print(dic)
    dic.setdefault("k4","v4")    #默认键值为None,不过可以添加值
    print(dic)
     
    #执行结果:
    OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
    OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')])
    

      

    #举一个实例:
    from collections import OrderedDict
    items = (
        ('A', 1),
        ('B', 2),
        ('C', 3)
    )
    regular_dict = dict(items)
    ordered_dict = OrderedDict(items)
    print 'Regular Dict:'
    for k, v in regular_dict.items():
        print k, v
    print 'Ordered Dict:'
    for k, v in ordered_dict.items():
        print k, v
    # Result:
    Regular Dict:
    A 1
    C 3
    B 2
    Ordered Dict:
    A 1
    B 2
    C 3

    三.python读文件保存到字典,修改字典并写入新文件

    tcode={}  
    transcode={}  
    def GetTcode():  
    #从文本中获取英文对应的故障码,并保存在tcode字典(故障码文本样例:oxff,0xff,0x00,0x01,    "Fuel Volume Regulator Control Circuit High")  
        with open('text_en.txt','r+')as fileone:  
            for line in fileone.readlines():  
                if not line:  
                    continue  
                line=line.strip()  
                titems=line.split('	')  
                strkey=titems[0].lower()  
                strtemp=titems[1]  
                tcode[strkey]=strtemp  
      
    def GetTransCode():  
    #从文本中获取中文对应的故障码,并保存在tcode字典(故障码文本样例:oxff,0xff,0x00,0x01,    "燃油调节器控制电路过高")  
        with open('text_cn.txt','r+') as fileone:  
            for line in fileone.readlines():  
                if not line:  
                    continue  
                line=line.strip()  
                transcode[line.split('	')[0].lower()]=line.split('	')[1]  
      
    def ReplaTransCode():  
    #将已经翻译的中文故障码在英文文本中用ID查找出来并替换,对新的tcode字典key进行排序,并写入新的文本中  
        for findkey in transcode.keys():  
            if tcode.get(findkey,-1)!= -1:  
                tcode[findkey]=transcode[findkey]  
        templine=[]  
        lkeys=tcode.keys()  
        lkeys.sort()  
        for key in lkeys:  
            value=tcode.get(key)  
            key=key.upper().replace("0X","0x")  
            templine.append("%s	%s
    "%(key,value))  
        with open('text_trans.txt','w+') as filetwo:  
            filetwo.writelines(templine)  
      
      
    if __name__ == '__main__':  
        GetTcode()  
        GetTransCode()  
        ReplaTransCode() 
    

      

     

     

  • 相关阅读:
    6/10
    Alpha 冲刺5/10
    现场编程
    4/10
    3/10
    总结
    bbbbbeta
    总结
    beta 7
    beta 6
  • 原文地址:https://www.cnblogs.com/xiaobai-yemao/p/8696612.html
Copyright © 2011-2022 走看看