Working With the Python operator Module
In this section, you’ll learn about three of the higher-order functions that Python’s operator
module makes available to you: itemgetter()
, attrgetter()
, and methodcaller()
. You’ll learn how these allow you to work with Python collections in a range of useful ways that encourage a functional style of Python programming.
Selecting Values From Multidimensional Collections With itemgetter()
The first function that you’ll learn about is operator.itemgetter()
. In its basic form, you pass it a single parameter that represents an index. Then itemgetter()
returns a function that, when passed a collection, returns the element at that index.
To begin with, you create a list of dictionaries: