Extract indexed or keyed values using a reusable function.
What You Will Learn
itemgetter(index_or_key) calls item access on its operand. With multiple indexes it returns a tuple of corresponding values.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from operator import itemgetter
records = [{'name': 'Mia', 'score': 88}, {'name': 'Noah', 'score': 92}]
print(sorted(records, key=itemgetter('score'), reverse=True)[0]['name'])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: operator.
- The variable records holds the result of [{'name': 'Mia', 'score': 88}, {'name': 'Noah', 'score': 92}]. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression sorted(records, key=itemgetter('score'), reverse=True)[0]['name'] prints Noah. Compare that result with the rule above before you change the argument.
Expected output from the example:
Noah
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from operator import itemgetter
rows = [("A", 3), ("B", 1)]
print(sorted(rows, key=itemgetter(1)))
Expected output:
[('B', 1), ('A', 3)]
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Sort products by their numeric price field.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Asking for a dictionary key that is missing and expecting a default rather than KeyError.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Extract indexed or keyed values using a reusable function.
- itemgetter(index_or_key) calls item access on its operand.
- Apply this operation only after checking the assumptions and input conditions shown in the example.