I am new to Python and I was wondering if there is a more common way of sorting a dictionary in descending order than the way I'm doing it:
sorted_dictionary = sorted(dict.items(), key=lambda x: -x[1])
                There is a reverse option to sorted() you could use instead:
sorted(dict.items(), key=lambda kv: kv[1], reverse=True)
This produces the exact same output, and even works if the values are not numeric.
This should work
{k: v for k, v in sorted(dict.items(), key=lambda item: item[1], reverse = True)}
                        Python dictionary aren't sortable. Your sorted_dictionary output is not a dictionary but a list. You have to use OrderedDict
from collections import OrderedDict
sorted_dictionary = OrderedDict(sorted(dict.items(), key=lambda v: v, reverse=True))
                        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