码迷,mamicode.com
首页 > 编程语言 > 详细

Python中字典排序

时间:2014-11-11 20:30:30      阅读:346      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   sp   div   on   log   bs   

如字典dic={‘a‘:1,‘f‘:2,‘c‘:3,‘h‘:0};要对其进行排序:

函数原型:sorted(dic,value,reverse); 

  1. dic为比较函数;
  2. value为比较对象(键或值);
  3. reverse:注明升序还是降序,True--降序,False--升序(默认);
     1 import operator;    
     2 # 字典中排序
     3 def sortDict():
     4     dic={a:1,f:2,c:3,h:0};
     5     # 函数原型:sorted(dic,value,reverse)
     6     # 按字典中的键进行升序排序
     7     print("按键进行升序排序结果为:", 8           sorted(dic.items(),key=operator.itemgetter(0),reverse=False));
     9     # 按字典中的键进行降序排序
    10     print("按键进行降序排序结果为:",11           sorted(dic.items(),key=operator.itemgetter(0),reverse=True));
    12     # 按字典中的值进行升序排序
    13     print("按值进行升序排序结果为:",14           sorted(dic.items(),key=operator.itemgetter(1),reverse=False));
    15     # 按字典中的值进行降序排序
    16     print("按值进行降序排序结果为:",17           sorted(dic.items(),key=operator.itemgetter(1),reverse=True));

    运行结果为:

    1 >>> import randMatrix;
    2 >>> sortDict()
    3 按键进行升序排序结果为: [(a, 1), (c, 3), (f, 2), (h, 0)]
    4 按键进行降序排序结果为: [(h, 0), (f, 2), (c, 3), (a, 1)]
    5 按值进行升序排序结果为: [(h, 0), (a, 1), (f, 2), (c, 3)]
    6 按值进行降序排序结果为: [(c, 3), (f, 2), (a, 1), (h, 0)]

     iteritems()函数:

  •  iteritems()以迭代器对象返回字典键值对;

  • 和item相比:items以列表形式返回字典键值对
     1 >>> dic={a:1,f:2,c:3,h:0};
     2 >>> dic.items()
     3 dict_items([(f, 2), (h, 0), (c, 3), (a, 1)])
     4 >>> dic.iteritems()
     5 Traceback (most recent call last):
     6   File "<pyshell#34>", line 1, in <module>
     7     dic.iteritems()
     8 AttributeError: dict object has no attribute iteritems
     9 >>> print(dic.iteritems())
    10 Traceback (most recent call last):
    11   File "<pyshell#35>", line 1, in <module>
    12     print(dic.iteritems())
    13 AttributeError: dict object has no attribute iteritems

    在Python3.4.2中没有iteritems()函数,所以报错;

Python中字典排序

标签:style   blog   color   os   sp   div   on   log   bs   

原文地址:http://www.cnblogs.com/yuzhuwei/p/4090143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!