如字典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()函数,所以报错;