python學習:字典排序

來源:互聯網
上載者:User

標籤:template   get   operator   md5sum   modules   dir   os.path   for   imp   

按字典值排序 按照字典value排序,類似sort -k 命令 import operatorx= {1:2,3:4,4:3,2:1,0:0}sorted_x = sorted(x.iteritems(),key=operator.itemgetter(1))In [38]: sorted_xOut[38]: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  sorted_y = sorted(x.iteritems(),key=operator.itemgetter(1),reverse=True) 找出佔用空間大的檔案 os.walkos.path.getsizedict sort(top10)  #!/usr/bin/env python import osimport sysimport operator def gen_dic(topdir):    dic = {}    a = os.walk(topdir)    for p, d, f in a:        for i in f:            fn = os.path.join(p, i)            f_size = os.path.getsize(fn)            dic[fn] = f_size    return dic if __name__ == ‘__main__‘:    dic =  gen_dic(sys.argv[1])    sorted_dic = sorted(dic.iteritems(), key=operator.itemgetter(1),reverse=True)    for k, v in sorted_dic[:10]:        print k, ‘---->‘,v [[email protected] day2]# python 4_top10.py ../2_walk.py ----> 781./3_dup.py ----> 727./4_top10.py ----> 484./1_md5sum.py ----> 421./3_yield.py ----> 127./test/a ----> 0./test/b ----> 0  [[email protected] day2]# python 4_top10.py /etc/etc/selinux/targeted/policy/policy.24 ----> 8377047/etc/selinux/targeted/modules/active/policy.kern ----> 8377047/etc/pki/tls/certs/ca-bundle.trust.crt ----> 1066943/etc/pki/tls/cert.pem ----> 877042/etc/pki/tls/certs/ca-bundle.crt ----> 877042/etc/alternatives/libnssckbi.so.x86_64 ----> 709880/etc/services ----> 641020/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt ----> 359773/etc/selinux/targeted/modules/active/file_contexts.template ----> 296225/etc/selinux/targeted/modules/active/file_contexts ----> 290594   

python學習:字典排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.