Sort by values ​​(descending) and then by keys (ascending) in the Python dictionary

I have the following dictionaries:

mydict1 = {1: 11, 2: 4, 5: 1, 6: 1} mydict2 = {1: 1, 5: 1} 

For each of them, I would like to first sort by values ​​(descending), and then by keys (ascending), having received this output:

 out_dict1 = [((1, 11), (2, 4), (5, 1), (6, 1)] out_dict2 = [(1, 1), (5, 1)] 

How to do it?

I used this, but I can not achieve the result in two cases above:

 sorted(mydict.items(), key=lambda x: (x[1],x[0])) 
+5
source share
1 answer

Since you want to sort the values ​​in descending order, simply negate the value of the values ​​in the function passed to the key parameter, for example,

 sorted(mydict.items(), key=lambda x: (-x[1], x[0])) 

Now the values ​​will be sorted in descending order, and if the two values ​​are equal, the keys will be considered, and they will be sorted in ascending order.

+7
source

Source: https://habr.com/ru/post/1215963/


All Articles