Use the operator module when an operation needs to become a function. Its itemgetter function is especially useful as a sorting key: itemgetter('name') returns a function that retrieves the name value from each dictionary. section 4.11
Two practical patterns make the module useful:
- Replace a one-use named function or less-readable lambda with itemgetter when sorting records by one or more keys. section 4.11
- Build a dispatch table by storing operator functions as dictionary values, then select and call the function associated with an input symbol. section 7.7
- Handle structured input deliberately: unpack the result of split(), and use maxsplit when unrestricted splitting could produce too many values. section 7.7
Sort dictionaries without a custom key function
from operator import itemgetter for person in sorted(people, key=itemgetter('name')): print(person) Pass multiple keys to sort hierarchically: itemgetter('size', 'name') sorts by size first and name second. section 4.11
def add(a,b):
return a + b
def sub(a,b):
return a - b
def mul(a,b):
return a * b
def div(a,b):
return a / b
def pow(a,b):
return a ** b
def mod(a,b):
return a % b
def calc(to_solve):
operations = {'+' : add, #1
'-' : sub,
'*' : mul,
'/' : div,
'**' : pow,
'%' : mod}
op, first_s, second_s = to_solve.split() #2
first = int(first_s) #3
second = int(second_s)
return operations[op](first, second) #4
Inspect a complete calculator pattern that maps symbols such as + and ** to functions, parses three input fields, and invokes the selected operation. section 7.7

