Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary by value then by key [duplicate]

Tags:

python

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)] 
like image 992
Austin Salonen Avatar asked Oct 12 '11 15:10

Austin Salonen


People also ask

How do you sort a dictionary based on value and then by key?

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.

How do you sort a dictionary by value first and then by key Python?

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

How do you sort a dictionary according to values?

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.

Can we sort a dictionary with keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.


1 Answers

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.

like image 194
unutbu Avatar answered Sep 22 '22 14:09

unutbu