简体   繁体   中英

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

This can be done in one step using the right 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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