Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Sort nested dictionary by the second item in the value

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

like image 738
Brian Zheng Avatar asked Oct 29 '25 06:10

Brian Zheng


1 Answers

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])])
like image 133
Netwave Avatar answered Oct 31 '25 00:10

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!