operator.itemgetter(1) in python 1

operator.itemgetter(1) in python

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'}]

Here is what the above code is Doing:
1. We are using the sorted() function to sort the movies list.
2. We are using the key parameter to specify the key on the basis of which we want to sort the list.
3. We are using the itemgetter() function to specify the key.
4. We are passing the key as ‘date’ to the itemgetter() function.
5. The itemgetter() function returns a callable object that fetches the given item(s) from its operand.
6. The sorted() function sorts the list on the basis of the key returned by the itemgetter() function.

Similar Posts