Skip to main content
 首页 » 编程设计

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

2025年05月04日18qlqwjy

假设我有这样一本字典:

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,橙色”排在最后。我认为这样的事情会起作用:

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' 

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

请您参考如下方法:

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

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

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

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