繁体   English   中英

按值然后按键对字典排序

[英]sort a dictionary by value and then by keys

我有一本这样的字典:

genre_dict = dict()
genre_dict = {'Action':Action, 'Adventure':Adventure, 'Comedy':Comedy, 'History':History, 'Horror':Horror, 'Romance':Romance}
genre_dict = OrderedDict(genre_dict)

我想先按值递减排序,如果值相同,则按键(流派名称)递减排序。 例如:

Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1

我是通过lambda条件完成的,但是对我来说不起作用(最好说我不能)。

这可以在一个步骤中使用正确的完成key

OrderedDict(sorted(genre_dict.items(), key=lambda x: (-x[1],x[0])))

OrderedDict([('Action', 3),
             ('Comedy', 2),
             ('History', 2),
             ('Horror', 2),
             ('Romance', 2),
             ('Adventure', 1)])

本质上,排序是基于以下条件进行的:

[(-x[1],x[0]) for x in genre_dict.items()]

[(-3, 'Action'),
 (-1, 'Adventure'),
 (-2, 'Comedy'),
 (-2, 'History'),
 (-2, 'Horror'),
 (-2, 'Romance')]

这个小技巧将使tuple两个值的排序以ascending方式完成,这是默认的排序标准。 否则,我们必须首先对第二个字段执行降序排序,然后对第一个字段执行升序排序。

尝试这个

genre_dict = dict()
genre_dict = {'Action':3, 'Adventure':1, 'Comedy':2, 'History':2, 'Horror':2, 'Romance':2}
new_dict = OrderedDict(sorted(sorted([(k,genre_dict[k]) for k in genre_dict]), key=lambda x: -x[1]))
print(new_dict)

根据定义,词典是(键,值)对,其中每个键都有唯一的值对。 因此,输入无效。 如果输入有效,则程序将按预期运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM