Python 2.5 dictionary 2 key sort

后端 未结 6 1766
灰色年华
灰色年华 2021-01-01 19:47

I have a dictionary of 200,000 items (the keys are strings and the values are integers).

What is the best/most pythonic way to print the items sorted by descending v

6条回答
  •  不思量自难忘°
    2021-01-01 20:36

    You can't sort dictionaries. You have to sort the list of items.

    Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric.

    a = { 'key':1, 'another':2, 'key2':1 }
    
    b= a.items()
    b.sort( key=lambda a:(-a[1],a[0]) )
    print b
    

    Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.

    def valueKeyCmp( a, b ):
        return cmp( (-a[1], a[0]), (-b[1], b[0] ) )
    
    b.sort( cmp= valueKeyCmp )
    print b
    

    The more general solution is actually two separate sorts

    b.sort( key=lambda a:a[1], reverse=True )
    b.sort( key=lambda a:a[0] )
    print b
    

提交回复
热议问题