I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key to the dictionary.
I can sort on the keys, but how can I sort based on the values?
We have a function name as sorted() which you can use to sort the dictionary by value:
sorted(d.items(), key=lambda x: x)
This will sort the dictionary in ascending order.
To sort it in descending order just add reverse=True:
sorted(d.items(), key=lambda x: x, reverse=True)