itemgetter Sorts Records On Multiple Keys
Sort records on several fields at once with itemgetter: dept then salary ordering, one reverse flag for the whole tuple, and attrgetter for dataclass fields.
Code
from operator import itemgetter, attrgetter
# itemgetter 一次取多个键:sorted 的 key 直接支持多级排序
records = [
{"dept": "eng", "salary": 120, "name": "ada"},
{"dept": "ops", "salary": 95, "name": "grace"},
{"dept": "eng", "salary": 110, "name": "linus"},
{"dept": "ops", "salary": 99, "name": "jules"},
]
by_dept_then_salary = sorted(records, key=itemgetter("dept", "salary"))
for r in by_dept_then_salary:
print(f"{r['dept']:4s} {r['salary']:>4} {r['name']}")
# reverse 对整个元组生效:部门降序、组内薪水降序
top = sorted(records, key=itemgetter("dept", "salary"), reverse=True)
print("top:", [(r["dept"], r["salary"]) for r in top])
# 单键也行:min/max 与排序复用同一个 key
print("lowest salary:", min(records, key=itemgetter("salary"))["name"])
# dataclass 对象用 attrgetter 按属性取值
from dataclasses import dataclass
@dataclass
class Ticket:
severity: int
title: str
tickets = [Ticket(3, "flaky check"), Ticket(1, "outage"), Ticket(2, "slow query")]
print("by severity:", [t.title for t in sorted(tickets, key=attrgetter("severity"))])Output
Captured from a sandboxed run of this snippet in the build pipeline.
eng 110 linus
eng 120 ada
ops 95 grace
ops 99 jules
top: [('ops', 99), ('ops', 95), ('eng', 120), ('eng', 110)]
lowest salary: grace
by severity: ['outage', 'slow query', 'flaky check']How the snippet works
Count the class class as the entire surface area of itemgetter Sorts Records On Multiple Keys.
The file repeats itself only inside for r in by_dept_then_salary. Reach for operator and what you get is itemgetter, attrgetter, dataclass — that is the whole API contact area.
Module-level bindings hold the data — records, by_dept_then_salary, top, tickets — with no function scope in between.
Caveats
- Requires
operatoras a package; the snippet will not run without it.
Using it
The demo output is labeled (top:, lowest salary:, by severity:), so every printed line maps back to its originating operation.
Key statements
for r in by_dept_then_salary:
print(f"{r['dept']:4s} {r['salary']:>4} {r['name']}")
Interactive Tools for This Topic
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `records`, `by_dept_then_salary`, `top`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.