python 按从小到大的顺序组合成一个字典_Python实现字典排序、按照list中字典的某个key排序的方法示例...
本文實(shí)例講述了python實(shí)現(xiàn)字典排序、按照l(shuí)ist中字典的某個(gè)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按照l(shuí)ist中的字典的某key排序:
例子:
s=[
{"no":28,"score":90},
{"no":25,"score":90},
{"no":1,"score":100},
{"no":2,"score":20},
]
print "original s: ",s
# 單級(jí)排序,僅按照score排序
new_s = sorted(s,key = lambda e:e.__getitem__('score'))
print "new s: ", new_s
# 多級(jí)排序,先按照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}]
說(shuō)明
1.new_s和new_s2的區(qū)別在于當(dāng)score均為90的時(shí)候,重新按照no排序
2.順序?yàn)閺男〉酱?若在sorted函數(shù)的參數(shù)加上reverse = true則為從大到小
ps:這里再為大家推薦一款關(guān)于排序的演示工具供大家參考:
在線動(dòng)畫(huà)演示插入/選擇/冒泡/歸并/希爾/快速排序算法過(guò)程工具:
希望本文所述對(duì)大家python程序設(shè)計(jì)有所幫助。
希望與廣大網(wǎng)友互動(dòng)??
點(diǎn)此進(jìn)行留言吧!
總結(jié)
以上是生活随笔為你收集整理的python 按从小到大的顺序组合成一个字典_Python实现字典排序、按照list中字典的某个key排序的方法示例...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mysql 数据库 导入兼容_mysql
- 下一篇: python概念英文版_和我一起学pyt