Sorting in python using operator.itemgetter and operator.attrgetter

Siddharth Kshirsagar
2 min readJul 18, 2020

--

Photo by Edu Grande on Unsplash

There are many methods to sort elements in python but today we will be looking into sorting data types in python using operator.itemgetter and operator.attrgetter.

1. Understanding operator.itemgetter(attribute) or operator.itemgetter(*attribute)

Returns a callable object that fetches item from its operand’s __getitem__()

i. Using itemgetter on a dictionary to retrieve key-value pair .

from operator import itemgetteritemgetter('car_name')({'car_name':'x4','company':'BMW'})output: 'x4'

ii. Using itemgetter to retrieve elements of a list.

itemgetter(2)([1,2,3,4,5])output: 3

2. Understanding operator.attrgetter(attribute) or operator.attrgetter(*attribute)

returns a callable object that fetches attribute from it's operand.

from operator import attrgetterclass Movie:  def __init__(self,name,date):       self.name = name       self.date = datemovie = Movie('TheDarkKnight',"2012")

Retriving the name and (name & date)attribute of movie object

attrgetter('name')(movie)  Output: 'TheDarkKnight'attrgetter('name','date')(movie)  Output: ('TheDarkKnight', '2012')

3. Using these functions for sorting

Below are the movies of marvel released in April and we want to sort them according to date and name we can use itemgetter

movies = [{'name':'Avengers Endgame','date':'26/4/2019'},          {'name':'Iron Man 3','date':'26/4/2013'},          {'name':'Avengers: Age of Ultron','date':'24/4/2013'}
]

Sorting according to ‘name’

sorted(movies, key=itemgetter('name'))#equivalent to "sorted(movies, key = lambda x: x['name'])"Output:[{'name': 'Avengers Endgame', 'date': '26/4/2019'},
{'name': 'Avengers: Age of Ultron', 'date': '24/4/2013'},
{'name': 'Iron Man 3', 'date': '26/4/2013'}]

Sorting according to ‘date’

sorted(movies, key=itemgetter('date'))
#equivalent to "sorted(movies, key = lambda x: x['date'])"
Output: [{'name': 'Avengers: Age of Ultron', 'date': '24/4/2013'},
{'name': 'Iron Man 3', 'date': '26/4/2013'},
{'name': 'Avengers Endgame', 'date': '26/4/2019'}]

Sorting according to ‘name’ and ‘date’ equivalent

sorted(movies ,key = itemgetter('name','date')) #equivalent to "sorted(movies, key = lambda x: (x['name],x['date']))"[{'name': 'Avengers Endgame', 'date': '26/4/2019'},
{'name': 'Avengers: Age of Ultron', 'date': '24/4/2013'},
{'name': 'Iron Man 3', 'date': '26/4/2013'}]

so as we can see both lambda and itemgetter have the same functionality but itemgetter is a bit faster than lambda so when execution speed and memory are a concern itemgetter is recommended.

4. Using attrgetter for sorting objects.

For example, you have objects that need to be sorted according to one of their attributes but in python, there is no way we can do this at this point attrgetter comes to rescue. let's continue with the same example as above.

class Movie:    def __init__(self,movie_name,movie_date):        self.movie_name = movie_name
self.movie_date = movie_date
def __repr__(self): return 'Movie({},{})'.format(self.movie_name,self.movie_date)movies = [Movie('Avengers Endgame','26/4/2019'),Movie('Iron Man 3','26/4/2013'), Movie('Avengers: Age of Ultron','24/4/2013')]

Now let's sort the movie objects according to the release date

sorted(movies,key=attrgetter('movie_date'))
# equavilent to sorted(movies, key= lambda x : x.movie_date)
Output: [Movie(Avengers: Age of Ultron,24/4/2013),
Movie(Iron Man 3,26/4/2013),
Movie(Avengers Endgame,26/4/2019)]

Reference: Jones, D., 2013. Python Cookbook, 3Rd Edition. O’Reilly Media, Inc.

--

--

No responses yet