How to Use the Python operator.itemgetter() Function

Contents
In this article, you will learn how to use the Python operator.itemgetter() function.
Python operator.itemgetter() Function
operator.itemgetter
is a function in the operator module in Python that can be used to extract an item or items from an object. It is often used to extract specific items from a list of dictionaries or other objects that are indexable. The itemgetter function takes one or more indices as arguments and returns a callable object that can be used to extract the desired items.
Here’s an example of how you could use operator.itemgetter to extract the “name” item from a list of dictionaries:
import operator
people = [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]
get_name = operator.itemgetter("name")
names = [get_name(person) for person in people]
print(names)
# Output
# ['John', 'Jane']
In the example above, we import the operator module and create a list of dictionaries called people. Then, we use operator.itemgetter to create a callable object get_name that will extract the “name” item from each dictionary. Finally, we use a list comprehension to apply the get_name callable to each dictionary in the people list and store the results in a new list called names.
You can also pass multiple indices to itemgetter to extract multiple items from each object:
import operator
people = [{"name": "John", "age": 30, "city": "New York"},
{"name": "Jane", "age": 25, "city": "London"}]
get_name_age = operator.itemgetter("name", "age")
names_and_ages = [get_name_age(person) for person in people]
print(names_and_ages)
# Output
# [('John', 30), ('Jane', 25)]
In this example, we use operator.itemgetter to create a callable object get_name_age that will extract both the “name” and “age” items from each dictionary. When we apply the get_name_age callable to each dictionary in the people list, it returns a tuple of the extracted items.