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实用编程技巧进阶

原文地址:https://www.cnblogs.com/marton/p/10745695.html