Python字典减少排序

时间:2015-12-07 11:55:17

标签: python-3.x

我想对字典进行排序。

dic = { "one" = 5, "two" = 8, "three" = 1, "four" = 3}
输出应该是:

("two", 8)
("one", 5)
("four", 3)
("three", 1)

最简单的方法是什么?

2 个答案:

答案 0 :(得分:1)

sorted支持关键字reverse。将其设置为True以获得反向排序顺序。

>>> dic = {"one": 5, "two": 8, "three": 1, "four": 3}

一种方式:

>>> [(k, dic[k]) for k in sorted(dic, key=dic.get, reverse=True)]
[('two', 8), ('one', 5), ('four', 3), ('three', 1)]

或:

>>> from operator import itemgetter
>>> sorted(dic.items(), key=itemgetter(1),  reverse=True)
[('two', 8), ('one', 5), ('four', 3), ('three', 1)]

此处itemgetter(1)lambda x: x[1]的作用相同,后者相当于:

def get_index_one(x):
    return x[1]

>>> sorted(dic.items(), key=get_index_one,  reverse=True)
[('two', 8), ('one', 5), ('four', 3), ('three', 1)]

答案 1 :(得分:1)

略有不同的方式:

>>> dic = { "one" : 5, "two" : 8, "three" : 1, "four" : 3}
>>> sorted(dic.items(), key = lambda x:x[1],reverse = True)
[('two', 8), ('one', 5), ('four', 3), ('three', 1)]