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.
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value?rq=1

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:-

Operator_module

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:-

https://docs.python.org/2/library/operator.html#operator.itemgetter
https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions
http://stackoverflow.com/questions/11287207/why-should-i-use-operator-itemgetterx-instead-of-x
http://stackoverflow.com/questions/18595686/how-does-operator-itemgetter-and-sort-work-in-python

-jigsaw

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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