keenns12 keenns12 - 1 year ago 68
Python Question

Sorting a dictionary by REVERSE VALUE then NON-REVERSE KEY

I have a dictionary containing string keys and int values that I want to be sorted. I want it to first be sorted by decreasing value number, then in alphabetical order.

For example if you had a dictionary containing:

my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}

The resulting sorted list would contain:

{('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)

Currently I'm using the following:

my_list = sorted(my_dict.items(), key=lambda x: (x[1],x[0])

I get a list sorted first in ascending value order and then in alphabetical.

How can I reverse the values but not the keys? I know you can pass a third parameter
to the
method, but it either does or does not reverse BOTH keys and values. How can sort by just one reversal? Thanks for any help!

Answer Source

Just use negate the value and use it as primary key:

>>> my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}
>>> sorted(my_dict.items(), key=lambda x: (-x[1], x[0]))
[('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)]