Sort dictionary by integers of dictionary keys

前端 未结 2 1277
天命终不由人
天命终不由人 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).

提交回复
热议问题