按字典键的整数对字典进行排序

gam*_*int 1 python sorting dictionary

假设我有一本这样的字典:

thedict={'1':'the','2':2,'3':'five','10':'orange'}
Run Code Online (Sandbox Code Playgroud)

我想按键对这本字典进行排序。如果我执行以下操作:

for key,value in sorted(thedict.iteritems()):
     print key,value
Run Code Online (Sandbox Code Playgroud)

我会得到

1 the
10 orange
2 2
3 five
Run Code Online (Sandbox Code Playgroud)

因为键是字符串而不是整数。我想对它们进行排序,就好像它们是整数一样,因此条目“10,orange”排在最后。我认为这样的事情会起作用:

for key,value in sorted(thedict.iteritems(),key=int(operator.itemgetter(0))):
    print key,value
Run Code Online (Sandbox Code Playgroud)

但这产生了这个错误:

TypeError: int() argument must be a string or a number, not 'operator.itemgetter'
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?谢谢!

Gav*_*n H 5

我认为您可以使用 lambda 表达式轻松做到这一点:

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

问题是您正在将一个可调用对象传递给int()内置函数并尝试使用int()调用的返回值作为键的可调用对象。您需要为 key 参数创建一个可调用对象。

你得到的错误基本上告诉你你不能int()用 operator.itemgetter (callable) 调用,你只能用字符串或数字调用它。