Sort dictionary by integers of dictionary keys

前端 未结 2 1270
天命终不由人
天命终不由人 2021-01-23 08:18

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

相关标签:
2条回答
  • 2021-01-23 08:41

    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).

    0 讨论(0)
  • 2021-01-23 08:53

    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.

    0 讨论(0)
提交回复
热议问题