Sorting With Key Functions

Sort anything with key functions — multi-field tuples, case-insensitive text, reverse runs — instead of comparison callback pyramids.

PythonData Integrity

Code

pythonsnippet
26 lines
def main() -> None:
    rows = [
        {'name': 'beta', 'score': 7},
        {'name': 'Alpha', 'score': 9},
        {'name': 'alpha', 'score': 9},
        {'name': 'gamma', 'score': 7},
    ]

    # 单键排序:key 提取比较字段
    by_score = sorted(rows, key=lambda r: r['score'])
    print([r['name'] for r in by_score])

    # 多键:元组主次序;大小写不敏感用 lower
    by_name = sorted(rows, key=lambda r: (r['score'], r['name'].lower()))
    print([(r['name'], r['score']) for r in by_name])

    # 逆序只翻主键方向
    desc = sorted(rows, key=lambda r: r['score'], reverse=True)
    print([r['name'] for r in desc])

    # sorted 稳定性:同键保持原顺序(Timsort 保证)
    print('stable:', [r['name'] for r in sorted(rows, key=lambda r: -r['score'])][:2])


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

['beta', 'gamma', 'Alpha', 'alpha']
[('beta', 7), ('gamma', 7), ('Alpha', 9), ('alpha', 9)]
['Alpha', 'alpha', 'beta', 'gamma']
stable: ['Alpha', 'alpha']

How it works

Sorting With Key Functions comes down to the function main.

Putting it to use

The run emits 1 labeled section — stable: — one per step.

Output is labeled for readability — expect lines prefixed with stable:.

Interactive Tools for This Topic

FAQ

What does Sorting With Key Functions print when run?
Run it as a complete program — the output lines carry labels such as `stable:`.