CKTIS / Python
operator.itemgetter
Creates a callable object that later retrieves items from its operand.
Version: Python 3.14; repository image, production runtime not attested
Syntax
operator.itemgetter(item, /, *items)Creates a callable object that later retrieves items from its operand.
With one key the callable returns the item itself. With several keys it returns a tuple in the requested order. A dictionary key, a sequence index or even a slice works when the input supports that subscription. The selectors are positional-only. The factory returns a callable itemgetter object; itemgetter(item=0) raises TypeError.
Use the callable as a sorting key to extract a field from each record. Errors come from the actual lookup, so a missing dictionary key raises KeyError when the callable is invoked, not when it is created.
Examples
from operator import itemgetter
records = [{"id": 2, "score": 8}, {"id": 1, "score": 5}]
by_score = sorted(records, key=itemgetter("score"))
print([row["id"] for row in by_score])
print(itemgetter("id", "score")(by_score[0]))
try:
itemgetter("rank")(by_score[0])
except KeyError as error:
print(type(error).__name__)
Result
[1, 2] (1, 5) KeyError
Use the callable as a sorting key to extract a field from each record. Errors come from the actual lookup, so a missing dictionary key raises KeyError when the callable is invoked, not when it is created.