我想对字典进行排序。
dic = { "one" = 5, "two" = 8, "three" = 1, "four" = 3}
输出应该是:
("two", 8)
("one", 5)
("four", 3)
("three", 1)
最简单的方法是什么?
答案 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)]