0

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.

1 Answer 1

1

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

output:

[('first', [5, 46]), ('second', [3, 59]), ('third', [1, 89])]
Sign up to request clarification or add additional context in comments.

1 Comment

I tried that, it would give a string index out of range error. Edit: WHOOPS. I misread it, I didn't read that you used .items() on the dictionary. Now that works, thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.