Python 3.6.2,使用来自operator的itemgetter - > TypeError:' int'对象不可订阅

时间:2017-08-28 20:00:35

标签: python python-3.x dictionary

我有一个样本字典:

sample = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

目标:

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

[(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]

我试过了:

import operator as o   
lst1 = sorted(sample, key = o.itemgetter(0))

以下是错误

Traceback (most recent call last):
  File "", line 1, in 
    lst1 = sorted(sample, key = o.itemgetter(0))
TypeError: 'int' object is not subscriptable

不确定我错过了什么。

1 个答案:

答案 0 :(得分:2)

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

trait SameShape[A, B]

object SameShape {
  implicit def instance[A, B, S]
    (implicit a: Generic.Aux[A, S], b: Generic.Aux[B, S]): SameShape[A, B] =
      new SameShape[A, B] {}
}

(对于这种情况,钥匙有些多余,但不会受到伤害。)