September 12, 2018

Dynamo: Sorting a List of Lists by a Value in the Sub-List in Python

I had a list that was composed of sub-lists, each sublist contained a Sheet Object and the values of three parameters associated with that Sheet, including the Sheet Number. I wanted to be able to sort the sub-lists in ascending order of the Sheet Number value in each sublist. I found the following Python code does the job:
sortedLists = sorted(listOfLists, key=lambda x: x[index])
where index is the index of the item in the sub-list on which you want to do the sorting.

For example, given a list with four sublists, similar to that in the image below,
where the index of the Sheet Number in each list is 1, the code below
will sort the sub-lists by the item in index 1 of each sub-list, with a result of

This page on the stackoverflow website helped me work this out. Two additional notes:
  • If you want to replace the original list with the sorted list, you can use this syntax:

    listOfLists.sort(key=lambda x: x[index]).

  • If you want to sort in descending order, add reverse=true as a parameter:

    sortedLists = sorted(listOfLists, key=lambda x: x[index], reverse = true)


    listOfLists.sort(key=lambda x: x[index], reverse = true).

No comments: