如何讓字典有序
問題舉例:
統計學生的成績和名次,讓其在字典中按排名順序有序顯示,具體格式如下
{'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實用編程技巧進階