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

How to use a lambda function to sort a dictionary with a nested list?

I’ve been trying to sort a dictionary based on largest to lowest values. The dictionary is structured like this:

testing = {"third":[1,89],"first":[5,46],"second":[3,59]}

The issue I’m coming across is that I’m not entirely sure as to how I can sort this based on the second listed value, so I want to sort it based on 89, 46 and 59. Not the first 1,5,3.

The method I was currently using is:

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

print(sorted(testing,key=lambda x:x[1][-1]))

Which is sorting the dictionary, but not in the way I’m trying to get it to. Where second is being sorted for the first value.

I’m sure there’s a way to do this, I’m just not sure how to approach this lambda function. Any guidance would be greatly appreciate.

>Solution :

sorted(testing.items(), key=lambda x: x[1][1])?

output:

[('first', [5, 46]), ('second', [3, 59]), ('third', [1, 89])]
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