按照固定顺序迭代python字典

python字典对(key,value)的存储是无序的,因此直接迭代输出字典(key,value)对是无规律的;如果想按照某个顺序来,可以用列表来实现。如果由于业务上的原因,在输出字典(key,value)时不得不按某个顺序进行输出,可以考虑下面几种方法。

背景:

 我有一个字典是这个样子的dic = {'lee':100,'tom':90,'jessica':80,'mary':70},key值是学生姓名,value值是分数,要求输出字典(key,value)对时,按照(lee,100),(tom,90),(jessica,80),(mary,70)这个顺序来,问如何实现?

1.最简单的直接写死输出顺序

 1 In [145]: dic
 2 Out[145]: {'jessica': 80, 'lee': 100, 'mary': 70, 'tom': 90}
 3 
 4 In [146]: print dic['lee']
 5 100
 6 
 7 In [147]: print dic['tom']
 8 90
 9 
10 In [148]: print dic['jessica']
11 80
12 
13 In [149]: print dic['mary']
14 70

2.设置一个列表来保存key值的顺序

 1 In [142]: dic
 2 Out[142]: {'jessica': 80, 'lee': 100, 'mary': 70, 'tom': 90}
 3 
 4 In [143]: keys = ['lee','tom','jessica','mary']
 5 
 6 In [144]: for key in keys:
 7    .....:     print key,dic[key]
 8    .....:
 9 lee 100
10 tom 90
11 jessica 80
12 mary 70

3.使用内建的sorted函数,将字典转成一个有序的列表元组形式

 1 In [172]: dic
 2 Out[172]: {'jessica': 80, 'lee': 100, 'mary': 70, 'tom': 90}
 3 
 4 In [173]: def mycmp(x,y):
 5    .....:     d = {'lee':1,'tom':2,'jessica':3,'mary':4}
 6    .....:     x = d[x]
 7    .....:     y = d[y]
 8    .....:     if x > y:
 9    .....:         return 1
10    .....:     elif x == y:
11    .....:         return 0
12    .....:     else:
13    .....:         return -1
14    .....:
15 
16 In [174]: dic.items()
17 Out[174]: [('jessica', 80), ('mary', 70), ('lee', 100), ('tom', 90)]
18 
19 In [175]: sorted(dic.items(),cmp=mycmp,key=lambda x:x[0])
20 Out[175]: [('lee', 100), ('tom', 90), ('jessica', 80), ('mary', 70)]
21 
22 In [176]: for item in sorted(dic.items(),cmp=mycmp,key=lambda x:x[0]):
23    .....:     print item[0],item[1]
24    .....:
25 lee 100
26 tom 90
27 jessica 80
28 mary 70

4.使用有序字典OrderedDict来实现

 1 In [178]: from collections import OrderedDict
 2 
 3 In [179]: d = OrderedDict()
 4 
 5 In [180]: d['lee'] = 100
 6 
 7 In [181]: d['tom'] = 90
 8 
 9 In [182]: d['jessica'] = 80
10 
11 In [183]: d['mary'] = 70
12 
13 In [184]: d
14 Out[184]: OrderedDict([('lee', 100), ('tom', 90), ('jessica', 80), ('mary', 70)])
15 
16 In [185]: d.items()
17 Out[185]: [('lee', 100), ('tom', 90), ('jessica', 80), ('mary', 70)]
18 
19 In [186]: for key in d:
20    .....:     print key,d[key]
21    .....:
22 lee 100
23 tom 90
24 jessica 80
25 mary 70
26 
27 In [187]:

如果你有什么好的方法,欢迎留言…-^^-…

参考资料:

http://pythonic.zoomquiet.io/data/20111219235951/index.html

http://zhoutall.com/archives/497

http://www.zlovezl.cn/articles/collections-in-python/