這篇文章主要介紹Python怎么實現字典排序、按照list中字典的某個key排序,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
1.給字典按照value按照從大到小排序
排序
dict = {'a':21, 'b':5, 'c':3, 'd':54, 'e':74, 'f':0}
new_dict = sorted(dict.iteritems(), key=lambda d:d[1], reverse = True)
print new_dict輸出:
[('e', 74), ('d', 54), ('a', 21), ('b', 5), ('c', 3), ('f', 0)]
2. python按照list中的字典的某key排序:
例子:
s=[
{"no":28,"score":90},
{"no":25,"score":90},
{"no":1,"score":100},
{"no":2,"score":20},
]
print "original s: ",s
# 單級排序,僅按照score排序
new_s = sorted(s,key = lambda e:e.__getitem__('score'))
print "new s: ", new_s
# 多級排序,先按照score,再按照no排序
new_s_2 = sorted(new_s,key = lambda e:(e.__getitem__('score'),e.__getitem__('no')))
print "new_s_2: ", new_s_2輸出:
original s: [{'score': 90, 'no': 28}, {'score': 90, 'no': 25}, {'score': 100, 'no': 1}, {'score': 20, 'no': 2}]
new s: [{'score': 20, 'no': 2}, {'score': 90, 'no': 28}, {'score': 90, 'no': 25}, {'score': 100, 'no': 1}]
new_s_2: [{'score': 20, 'no': 2}, {'score': 90, 'no': 25}, {'score': 90, 'no': 28}, {'score': 100, 'no': 1}]
說明
1.new_s和new_s2的區別在于當score均為90的時候,重新按照no排序
2.順序為從小到大,若在sorted函數的參數加上reverse = True則為從大到小
以上是“Python怎么實現字典排序、按照list中字典的某個key排序”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。