Sorting dictionary by values without losing information of keys
This question already has an answer here:
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)
.
下一篇: 按值排序字典而不丢失密钥信息