按字典键的整数排序字典

1 投票
2 回答
3410 浏览
提问于 2025-04-18 07:15

假设我有一个字典,长这样:

thedict={'1':'the','2':2,'3':'five','10':'orange'}

我想按照键来排序这个字典。如果我这样做:

for key,value in sorted(thedict.iteritems()):
     print key,value

我会得到

1 the
10 orange
2 2
3 five

因为这些键是字符串,而不是整数。我想把它们当成整数来排序,所以像“10,orange”这样的条目应该排在最后。我以为这样做可以:

for key,value in sorted(thedict.iteritems(),key=int(operator.itemgetter(0))):
    print key,value

但这产生了这个错误:

TypeError: int() argument must be a string or a number, not 'operator.itemgetter'

我哪里做错了呢?谢谢!

2 个回答

2

这是一个例子,说明人们对 itemgetter 的迷恋有时会让他们走入误区。其实,直接使用 lambda 就可以了:

>>> thedict={'1':'the','2':2,'3':'five','10':'orange'}
>>> sorted(thedict.iteritems(), key=lambda x: int(x[0]))
[('1', 'the'), ('2', 2), ('3', 'five'), ('10', 'orange')]

问题在于 int(operator.itemgetter(0)) 被立即计算出来了,这样才能把它作为参数传给 sorted。所以你先创建了一个 itemgetter,然后试图对它使用 int(这不行,因为它既不是字符串也不是数字)。

5

我觉得你可以很简单地用一个lambda表达式来实现这个。

sorted(thedict.iteritems(), key=lambda x: int(x[0]))
# with Python3, use thedict.items() for an iterator

问题在于,你把一个可调用的对象传给了内置的int()函数,然后试图把int()的返回值当作键的可调用对象。你需要为键的参数创建一个可调用的对象。

你遇到的错误基本上是在告诉你,不能用一个operator.itemgetter(可调用对象)来调用int(),你只能用字符串或数字来调用它。

撰写回答