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