python 字典(dict)的特点就是⽆序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以⽤下⾯的⽅法来进⾏:
1 下⾯的是按照value的值从⼤到⼩的顺序来排序。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)print(dict)
输出的结果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
下⾯我们分解下代码:
print dic.items() 得到[(键,值)]的列表。
然后⽤sorted⽅法,通过key这个参数,指定排序是按照value,也就是第⼀个元素d[1的值来排序。reverse = True表⽰是需要翻转的,默认是从⼩到⼤,翻转的话,那就是从⼤到⼩。2 对字典按键(key)排序:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}dict= sorted(dic.items(), key=lambda d:d[0]) print dict
以上就是⼩编为⼤家带来的python 字典(dict)按键和值排序全部内容了,希望⼤家多多⽀持~
因篇幅问题不能全部显示,请点此查看更多更全内容