Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sorting

I have the following dictionaries:

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

For each one of them I'd like to first sort by values (descending) and then keys (ascendingly), yielding this output:

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

What's the way to do it?

I used this but cannot get the result consistently for two cases above:

sorted(mydict.items(), key=lambda x: (x[1],x[0]))
like image 996
pdubois Avatar asked Mar 24 '15 03:03

pdubois


People also ask

How do you sort a dictionary by value in ascending order python?

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.

How do you sort a dictionary based on value descending?

Sorting a dict by value descending using list comprehension. The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True . If you are using Python 3.7, regular dict s are ordered by default.


1 Answers

Since you want to sort the values in descending order, just negate the value of values in the function passed to the key parameter, like this

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

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

like image 183
thefourtheye Avatar answered Nov 15 '22 00:11

thefourtheye