Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort dict by a dict value

I’m trying to sort a dict‘s value where the value is a dict where the value is a list of two integers. I’m trying to sort the rows in the inner dict by the first integer of the list.

This is the value of the dict:

{'EQUITY': {'CA': [15, 20], 'US': [25, 30]}, ... }

Here, the ‘US’ row should come before the ‘CA’ row after sorting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I’m currently trying:

dict(sorted(data.items(), key=lambda item: item[1][ ?? ], reverse=True))

how should I index into the inner dict from here ??

Thanks in advance for the help.

>Solution :

You are almost there. Try the following, which uses dict comprehension and sorted with key parameter:

dct = {'EQUITY': {'CA': [15, 20], 'US': [25, 30]}, 'FUTURE': {'CA': [5, 5], 'US': [10, 2]}}

output = {k: dict(sorted(d.items(), key=lambda item: item[1][0], reverse=True)) for k, d in dct.items()}

print(output)
# {'EQUITY': {'US': [25, 30], 'CA': [15, 20]}, 'FUTURE': {'US': [10, 2], 'CA': [5, 5]}}

Here, each item of d.items() would be a tuple like ('CA', [15, 20]). Therefore, to sort by 15, you need item[1][0].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading