1 下面的是按照value的值從大到小的順序來排序。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict
輸出的結果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
下面我們分解下代碼
print dic.iteritems() 得到[(鍵,值)]的列表。
然後用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.iteritems(), key=lambda d:d[0]) d[0]表示字典的鍵
print dict