Python中字典排序

如字典dic={'a':1,'f':2,'c':3,'h':0};要對其進行排序:shell

函數原型: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));

    運行結果爲:spa

    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()函數:code

  •  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()函數,因此報錯;blog

相關文章
相關標籤/搜索