Sort dict by highest value?

This question already has an answer here:

  • How do I sort a dictionary by value? 38 answers
  • How to sort a Python dict by value 5 answers

  • sorted(myDict, key=myDict.get, reverse=True)
    

    Here's one way of doing it:

    >>> myDict = {'seven': 7, 'four': 4, 'one': 1, 'two': 2, 'five': 5, 'eight': 8} 
    >>> sorted(myDict.iterkeys(), key=lambda k: myDict[k], reverse=True)
    ['eight', 'seven', 'five', 'four', 'two', 'one']
    

    (Inspired by this answer)

    It uses the built-in function sorted (with reverse=True to get highest to lowest), and the key argument is a function that sets the sort key. In this case it's a lambda that fetches the corresponding dict value, but it can be pretty much anything. For example, you could use operator.itemgetter(1) or myDict.get as shown by other answers, or any other sorting function (other than by value).


    You can use items to get a list of pairs key-value and sorted to sort them using your criteria:

    myList = sorted(myDict.items(), key=lambda x: x[1], reverse=True)
    

    If you're using ipython, you can type myDict. tabtab and you're get a list of all functions. You can also type print myDict.items.__doc__ and get a quick documentation.

    The key parameter is a function to apply to an element before it gets compared. As items returns a list of pairs and sorting is done on pairs' second element, key is a function which gets the second element from a tuple.

    Of course, it is possible to get rid of the items call, using:

    myList = sorted(myDict, key=myDict.get, reverse=True) #posted in another answer
    
    链接地址: http://www.djcxy.com/p/18152.html

    上一篇: 按日期时间值对Python字典进行排序

    下一篇: 按照最高值排序字典?