0 votes
1 view
in Python by (20.3k points)

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?

1 Answer

0 votes
by (50.7k points)
selected by
Best answer

We have a function name as sorted() which you can use to sort the dictionary by value:

sorted(d.items(), key=lambda x: x[1])

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[1], reverse=True)