Sort a list of tuples depending on two elements

PythonSortingPython 3.xTuples

Python Problem Overview


> Possible Duplicate:
> python: how to sort a complex list on two different keys

I've got a list of tuples. I want to sort them depending two elements. Here is following example

unsorted = [('a', 4, 2), ('a', 4, 3), ('a', 7, 2), ('a', 7, 3), ('b', 4, 2), ('b', 4, 3), ('b', 7, 2), ('b', 7, 3)]
sorted   = [('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3), ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)]

I know how to sort them on the second element:

sorted(unsorted, key = lambda element : element[1])

But how to do that with two keys?

Python Solutions


Solution 1 - Python

sorted(unsorted, key=lambda element: (element[1], element[2]))

I've assumed an order for the keys from the sample output.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRazerView Question on Stackoverflow
Solution 1 - PythonMichael J. BarberView Answer on Stackoverflow