Sorting using Operator module in Python

Today I was asked a question to sort the items in a dictionary based on the values rather than how it is done traditionally using keys. This introduced me to the operator module in Python, which facilitates it.

First of, you should note than dictionaries in python cannot be sorted, but they can be displayed in a sorted format, even according to values.

Check out this answert on Stack Overflow.

Try and make sense of the following python script:-

dict_sort using values

As you can see, simply printing sorted(dict_name) will display the dictionary sorted on the basis of the key.
Using the statement sorted(dict_name , key = dict_name.get) will only give us a list of the keys of the dictionary in a sorted manner.

To display the whole dictionary sorted on the basis of values, we write print sorted(dict_name.items() , key = operator.itemgetter(1) ). itemgetter() function is used to fetch items from an operand, which is the dictionary in this case.

I also wrote another script on itemgetter() function, to make its usage clear to the readers.

Try out the following script:-


In this script, I am working with a list containing tuples of values. I use itemgetter to access the items at the specified index in the list.

1.sorted(a), simply sorts the values on the basis of the first field, i.e the name.
2.In the 3rd case, sorted(a, key = operator.itemgetter(2)) sorts on the basis of the 3rd field in the tuple, which is the job field.
3. In the second line which says print sorted(a, key=operator.itemgetter(1,0) , I am including a provision for multiple fields of sorting. That is, if the values at the index 1, which is the age, are matching values, then we will resolve the sort using the the 3rd field, which is the job.

Hope this introduces you to the opeartor module in an easy manner.

Further links you can visit:-



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s