Explained Everything About Python itemgetter

In this article, we will be looking at the Python function .itemgetter() from the module operator. The standard library operator provides functions for mathematical, logical, arithmetical, bitwise, etc., operations, and sequence comparisons.

About the Function

operator.itemgetter() that fetches an “item” using the operand’s __getitem__() method. If multiple values are returned, the function returns them in a tuple. This function works with Python dictionaries, strings, lists, and tuples.

Parameters

operator.itemgetter(item) or operator.itemgetter(*item)

operator.itemgetter() takes an “item” or a pointer to an “item”. It can be of anything within Python’s pre-defined data types.

Returns

The function can be an element or of multiple elements from a sequence. They can be of any one of Python’s in-built data types.

Importing the Module

As for Python 3, this module is currently a part of the Python Standard Library Module. It comes under the “Functional Programming Modules” category. Also, you can try these commands using our online Python interpreter here.

import operator

Using operator.itemgetter() on Python Sequence Data Types

Using itemgetter() on a Python Dictionary

Retrieving the key/value of a dictionary. In the code below, we pass a dictionary sampleDict that consists of an entry.

import operator
sampleDict = {'Product':'iPhone 13 Pro Max','Company':'Apple'}
operator.itemgetter('Product')(sampleDict)

Output

iPhone 13 Pro Max

itemgetter() uses the key product in sampleDict and provides us with the value.

Using itemgetter() on a Python List

Applying the function on a list to retrieve an element. In this program, we are passing itemgetter() to a list sampleList.

import operator

sampleList = ["macOS", "Windows", "Linux"]

# Gets item from index "2"
operator.itemgetter(2)(sampleList)

Output

Linux

The function looks for the element at index “2” in the list sampleList. Eventually, it returns the element Linux.

Sorting a List of Dictionaries using operator.itemgetter()

In this program, we are sorting a list of dictionaries consisting of the top smartphone companies and the prices of their latest models.

Sorting by Name (Alphabetical Order)

Phones is a list that consists of three dictionaries of the phone’s name and price. We are using the function sorted() and passing the key as the element returned by operator.itemgetter('PhoneName')).

import operator
phones = [{'PhoneName':'Apple','PhonePrice': 113000},
          {'PhoneName':'Samsung','PhonePrice':109999},
          {'PhoneName':'OnePlus','PhonePrice':69000}
]
# Passing 'PhoneName' in itemgetter() to sort by the Company names
sorted(phones, key=operator.itemgetter('PhoneName'))

Output

[{'PhoneName': 'Apple', 'PhonePrice': 113000},
 {'PhoneName': 'OnePlus', 'PhonePrice': 69000},
 {'PhoneName': 'Samsung', 'PhonePrice': 109999}]

The dictionary is sorted in alphabetical order.

Sorting by Price (Lowest to Highest)

The function sorted takes the key value as the element returned by operator.itemgetter('PhonePrice')).

import operator
phones = [{'PhoneName':'Apple','PhonePrice': 113000},
          {'PhoneName':'Samsung','PhonePrice':109999},
          {'PhoneName':'OnePlus','PhonePrice':69000}     
]
# Passing 'PhonePrice' in itemgetter() to sort by the Phones' prices
sorted(phones, key=operator.itemgetter('PhonePrice'))

Output

[{'PhoneName': 'OnePlus', 'PhonePrice': 69000},
 {'PhoneName': 'Samsung', 'PhonePrice': 109999},
 {'PhoneName': 'Apple', 'PhonePrice': 113000}]

Therefore, sorting the list of dictionaries by price in ascending order.

Python .itemgetter() vs .attrgetter()

operator.itemgetter()operator.attrgetter()
Fetches an item using its operand’s getitem() functionFetches the attributes of an object
If more than one element from a sequence is requested, a tuple of elements is returned.If more than one attribute is requested, the function returns a tuple of attributes.
E.g., Returns a value of an in-built data type.E.g., Returns an object.

Common Errors with .itemgetter()

itemgetter() not defined.

import operator

b=[(7,1),(3,3),(4,2),(0,-1),(4,3)]
sorted(b,key=itemgetter(1)) # error occurs here

##### Output #####

# NameError: name 'itemgetter' is not defined

.itemgetter() is part of the module called operator. Hence, you must tell Python that you call a function from that module by calling an operator.itemgetter(). If you are going to be using just this function from the module, you can import just the function alone by writing:

from operator import itemgetter

Therefore, this allows you to call the function without mentioning the module it came from.

FAQs on Python itemgetter

Is Python .itemgetter() better than Python’s lambda function?

Between Python lambda and .itemgetter(), .itemgetter() is executed with much more speed and efficiency. .itemgetter() It also allows you to “get” multiple elements at once. Python lambda will enable you to do that, but the command is very long and repetitive.

Conclusion

Therefore, we have looked at the operator module’s Python .itemgetter() function and its application on sequential data types. We discussed how this function is different from another function in its module, .attrgetter().

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments