I have a dictionary like this:
{'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
I want to sort the dictionary by the second item in the value of each key from big to small, so the result I want is like this:
{'zzz':['zzz', 3], 'yyy':['yyy', 2], 'xxx':['xxx', 0]}
Is there any way to do that? Thank you! Note that there might be dictionary items that have the same values
In python versions were the dicts are ordered (CPython3.6m Python3.7+) use sorted with reverse activated and a custom key:
>>> d = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
>>> d = dict(sorted(d.items(), reverse=True, key=lambda x: x[1][1]))
>>> d
{'zzz': ['zzz', 3], 'yyy': ['yyy', 2], 'xxx': ['xxx', 0]}
If not (Python3.5 or lower), use OrderedDict:
>>> from collections import OrderedDict
>>> d = {'xxx':['xxx', 0], 'yyy':['yyy', 2], 'zzz':['zzz', 3]}
>>> d = OrderedDict(sorted(d.items(), reverse=True, key=lambda x: x[1][1]))
>>> d
OrderedDict([('zzz', ['zzz', 3]), ('yyy', ['yyy', 2]), ('xxx', ['xxx', 0])])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With