简体   繁体   English

按值然后按键对字典排序

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

I have a dictionary like this: 我有一本这样的字典:

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

I want to sort it decreasingly first by values and if the values were same sort it decreasingly by keys (name of genre). 我想先按值递减排序,如果值相同,则按键(流派名称)递减排序。 For example: 例如:

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

I did it by lambda condition but it didn't work for me(its better to say I couldn't). 我是通过lambda条件完成的,但是对我来说不起作用(最好说我不能)。

This can be done in one step using the right key : 这可以在一个步骤中使用正确的完成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)])

Essentially the sorting is taking place based on: 本质上,排序是基于以下条件进行的:

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

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

This little trick enables the sorting for both values in the tuple to be done in an ascending manner, which is the default ordering criteria. 这个小技巧将使tuple两个值的排序以ascending方式完成,这是默认的排序标准。 Otherwise we would have to first implement a descending sorting for the second field, and then an ascending one for the first. 否则,我们必须首先对第二个字段执行降序排序,然后对第一个字段执行升序排序。

Try this 尝试这个

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)

By definition, dictionaries are (key,value) pairs, where each key has a unique value pair. 根据定义,词典是(键,值)对,其中每个键都有唯一的值对。 So, the input is invalid. 因此,输入无效。 If the input is valid, the program works as expected. 如果输入有效,则程序将按预期运行。

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

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