python学习:字典排序

按字典值排序
 
按照字典value排序,类似sort -k 命令
 
import operator
x= {1:2,3:4,4:3,2:1,0:0}
sorted_x = sorted(x.iteritems(),
key=operator.itemgetter(1))
In [38]: sorted_x
Out[38]: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
 
 
sorted_y = sorted(x.iteritems(),
key=operator.itemgetter(1),reverse=True)
 
找出占用空间大的文件
 
os.walk
os.path.getsize
dict sort(top10)
 
 
#!/usr/bin/env python
 
import os
import sys
import 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
 
[root@web10 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
 
 
[root@web10 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
 
 
 
posted @ 2017-09-14 14:40  Oops!#  阅读(184)  评论(0编辑  收藏  举报