Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python字典递减排序_Python 3.x - Fatal编程技术网

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)]