This seems like it has to be a dupe but my SO-searching-fu is poor today...
Say I have a dictionary of integer key/values, how can I sort the dictionary by the values descending, then by the key descending (for common values).
Input:
{12:2, 9:1, 14:2} {100:1, 90:4, 99:3, 92:1, 101:1}
Output:
[(14,2), (12,2), (9,1)] # output from print [(90,4), (99,3), (101,1), (100,1), (92,1)]
To sort a dictionary by value then the key we can easily use the lambda and sorted function. In this example, we can set this reverse flag order as true which means the value will be in descending order.
The key=lambda x: (x[1],x[0]) tells sorted that for each item x in y. items() , use (x[1],x[0]) as the proxy value to be sorted. Since x is of the form (key,value) , (x[1],x[0]) yields (value,key) .
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
In [62]: y={100:1, 90:4, 99:3, 92:1, 101:1} In [63]: sorted(y.items(), key=lambda x: (x[1],x[0]), reverse=True) Out[63]: [(90, 4), (99, 3), (101, 1), (100, 1), (92, 1)]
The key=lambda x: (x[1],x[0])
tells sorted
that for each item x
in y.items()
, use (x[1],x[0])
as the proxy value to be sorted. Since x
is of the form (key,value)
, (x[1],x[0])
yields (value,key)
. This causes sorted
to sort by value
first, then by key
for tie-breakers.
reverse=True
tells sorted
to present the result in descending, rather than ascending order.
See this wiki page for a great tutorial on sorting in Python.
PS. I tried using key=reversed
instead, but reversed(x)
returns an iterator, which does not compare as needed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With