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