0 votes
1 view
in Python by (47.8k 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 (107k points)
edited 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)

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.8k points)
+1 vote
1 answer
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !