Python 3.6.2,使用操作符中的 itemgetter -> TypeError: 'int' object is not subscriptable

Sag*_*wda -1 python dictionary python-3.x

我有一个示例字典:

sample = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Run Code Online (Sandbox Code Playgroud)

客观的:

获取键上的(键,值)对的排序列表。
它应该看起来像这样:

[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
Run Code Online (Sandbox Code Playgroud)

我试过这个:

import operator as o   
lst1 = sorted(sample, key = o.itemgetter(0))
Run Code Online (Sandbox Code Playgroud)

以下是错误

回溯(最近一次调用最后一次):
  文件“”,第 1 行,位于
    lst1 = 排序(样本, key = o.itemgetter(0))
类型错误:“int”对象不可下标

不知道我错过了什么。

use*_*ica 5

如果要对键值对进行排序,请对键值对进行排序,而不是对字典进行排序:

sorted(sample.items(), key=operator.itemgetter(0))
#            ^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

(对于这种情况,密钥有点多余,但也没什么坏处。)