Sorting dictionary by values without losing information of keys

This question already has an answer here:

  • How do I sort a dictionary by value? 38 answers

  • If you want to keep the sorted result with a key/value structure I recommend collections.OrderedDict :

    from collections import OrderedDict
    from operator import itemgetter
    
    dct = {'Rick Porcello, Bos SP': 579.0, 'Chris Sale, CWS SP': 575.0, 'Justin Verlander, Det SP': 601.0, 'Madison Bumgarner, SF SP': 617.0, 'Max Scherzer, Wsh SP': 668.0, 'Johnny Cueto, SF SP': 584.0}
    
    OrderedDict(sorted(dct.items(), key=itemgetter(1), reverse=True))
    

    The key=itemgetter(1) defines that you sort by "values" and reverse=True tells sorted to sort in descending order.

    This gives:

    OrderedDict([('Max Scherzer, Wsh SP', 668.0),
                 ('Madison Bumgarner, SF SP', 617.0),
                 ('Justin Verlander, Det SP', 601.0),
                 ('Johnny Cueto, SF SP', 584.0),
                 ('Rick Porcello, Bos SP', 579.0),
                 ('Chris Sale, CWS SP', 575.0)])
    

    and can still be accessed like a normal dictionary:

    >>> odict['Chris Sale, CWS SP']
    575.0
    

    or iterate over it:

    >>> for name, value in odict.items():
    ...     print('{name}: {value}'.format(name=name, value=value))
    Max Scherzer, Wsh SP: 668.0
    Madison Bumgarner, SF SP: 617.0
    Justin Verlander, Det SP: 601.0
    Johnny Cueto, SF SP: 584.0
    Rick Porcello, Bos SP: 579.0
    Chris Sale, CWS SP: 575.0
    

    Given that it sorts the input it will scale with O(n logn) .

    链接地址: http://www.djcxy.com/p/18168.html

    上一篇: 为什么排序(字典)返回一个列表而不是字典?

    下一篇: 按值排序字典而不丢失密钥信息