Home > Software engineering >  How to use a lambda function to sort a dictionary with a nested list?
How to use a lambda function to sort a dictionary with a nested list?

Time:12-03

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:

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.

CodePudding user response:

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

output:

[('first', [5, 46]), ('second', [3, 59]), ('third', [1, 89])]
  • Related