Python 3.x Python字典递减排序
我想把我的字典分类Python 3.x Python字典递减排序,python-3.x,Python 3.x,我想把我的字典分类 dic = { "one" = 5, "two" = 8, "three" = 1, "four" = 3} 输出应为: ("two", 8) ("one", 5) ("four", 3) ("three", 1) 最简单的方法是什么?sorted支持关键字reverse。对于反向排序顺序,将其设置为True >>> dic = {"one": 5, "two": 8, "three": 1, "four": 3} 单向: >>> [
dic = { "one" = 5, "two" = 8, "three" = 1, "four" = 3}
输出应为:
("two", 8)
("one", 5)
("four", 3)
("three", 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)]
或:
这里的itemgetter(1)
与lambda x:x[1]
的作用相同,这反过来相当于:
def get_index_one(x):
return x[1]
i、 e
稍微不同的方式:
>>> 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)]
我想用下面的代码来做:对于排序中的项(dic.items(),key=lambda x:x[1]):但是我不能改变它,所以我可以对字典进行排序,因为字典构建是不正确的。应该是:
dic={“一”:5,“二”:8,“三”:1,“四”:3}
顺便说一句,这个问题好像是课堂作业。没有显示任何研究工作。
>>> sorted(dic.items(), key=get_index_one, reverse=True)
[('two', 8), ('one', 5), ('four', 3), ('three', 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)]