python数据结构-如何让字典有序


如何让字典有序

问题举例:

统计学生的成绩和名次,让其在字典中按排名顺序有序显示,具体格式如下

{'tom':(1, 99), 'lily':(2, 98), 'david':(3, 95)}

 

说明

python3.5中的dict是无序的,python3.6中的dict是有序的,

为了实现程序向后兼容,在使用有序字典时请使用collections中的OrderedDict

 

使用标准库collections中的OrderedDict

from random import shuffle
from collections import OrderedDict
from itertools import islice
stus = list("abcdefg")
print(stus)
shuffle(stus)
print(stus)

od = OrderedDict()
for i, stu in enumerate(stus, 1):
    od[stu] = i

print(od)
print(list(islice(od, 3, 5)))

 

参考资料:python3实用编程技巧进阶


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM