Let\'s say I have a dictionary like so:
thedict={\'1\':\'the\',\'2\':2,\'3\':\'five\',\'10\':\'orange\'}
and I want to sort this dictionary by
This is one of the times when people's inexplicable attraction to itemgetter
can lead them astray. Simply use a 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')]
The problem is that int(operator.itemgetter(0))
is being evaluated immediately, in order to pass it as an argument to sorted
. So you're building an itemgetter
, and then trying to call int
on it (which isn't working, because it's not a string or a number).
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
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.
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.