Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k 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?

closed

2 Answers

0 votes
by (106k 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:-

0 votes
by (107k points)

There is one package known as the operator, from that, we get one function known as itemgetter() function. 

This function will help us to get the object that will return a single element from an object.

For example:

import operator

dict1 = {1: 3, 2: 6}

get_item_with_key_2 = operator.itemgetter(2)

print(get_item_with_key_2(dict1))

From the above code, we will get the main element from the '2' key value.

Now we will use the items() function returns the key-value pairs of a dictionary in the form of a list of tuples values.

After that, we can arrange the list of tuples values by executing the itemgetter() function so that it can extract the second value of the tuple, that is all the values from the keys section from the dictionary.

Once all the values are in an arranged manner, we can simply create a dictionary based on those values. Refer to the below code:

import operator

d1 = {1: 1, 2: 9, 3: 4}

sort = sorted(d1.items(), key=operator.itemgetter(1))

print(sort)  # [(1, 1), (3, 4), (2, 9)]

sorted_dict = {k: v for k, v in sort}

print(sorted_dict) # {1: 1, 3: 4, 2: 9}

If you want to know more about Python programming, then refer to the course that will help you out in a better way. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...