按字典键的整数对字典进行排序 [英] Sort dictionary by integers of dictionary keys
问题描述
假设我有这样的字典:
thedict={'1':'the','2':2,'3':'five','10':'orange'}
,我想按键对这本字典进行排序.如果我执行以下操作:
and I want to sort this dictionary by key. If I do the following:
for key,value in sorted(thedict.iteritems()):
print key,value
我会得到
1 the
10 orange
2 2
3 five
因为键是字符串而不是整数.我想对它们进行排序,就好像它们是整数一样,因此条目"10,orange"排在最后.我以为这样的事情会起作用:
since the keys are strings and not integers. I want to sort them as if they are integers, so the entry "10,orange" comes last. I thought something like this would work:
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'
我在这里做错了什么?谢谢!
What am I doing wrong here? Thanks!
推荐答案
我认为您可以使用lambda表达式来做到这一点:
I think you could do that easy enough with a lambda expression:
sorted(thedict.iteritems(), key=lambda x: int(x[0]))
# with Python3, use thedict.items() for an iterator
问题是您将可调用对象传递给内置的int()
,并试图将int()
调用的返回值用作键的可调用对象.您需要为key参数创建一个callable.
The problem is that you are handing a callable object to the int()
builtin and trying to use the return value of the int()
call as a callable for the key. You need to create a callable for the key argument.
您得到的错误基本上告诉您,您不能使用操作符来调用int()
.itemgetter(可调用)只能使用字符串或数字来调用.
The error you are getting basically tells you that you can't call int()
with an operator.itemgetter (callable), you can only call it with a string or a number.
这篇关于按字典键的整数对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!