Occasionally, you'll want to sort your list based on something other than the string value of the list label. You can do that in wxPython, but it's a slightly more complicated process. First, you need to set item data for each item in the list, by using the SetItemData(item, data) method. The item is the index of the item within the (unsorted) list, and the data is whatever data you want to associate with that item. The data item must be an integer or a long value (due to the C++ expected data type), which limits the usefulness of this mechanism somewhat. To retrieve the item data for a row, use the method GetItemData(item).
Once you have the item data in place, you can use the method Sort-Items(func) to sort the items. The argument to the method is a Python callable object which takes in two integers. The function is called with the associated data of two list items to be compared—you don't get any reference to the rows themselves. The function should return a positive integer if the first item is greater than the second (meaning the first item should be earlier in the sorted list), a negative value if the first item is less than the second (meaning the first item is later in the sorted list), and zero if the two are equal. Although the most obvious way to implement this function is to just do a numerical comparison of the two items, that is by no means the only thing that you could do in the sort method. For instance, the data item could be a key in an external dictionary or list that has a more complex data item, which you could compare to determine sort order.
Was this article helpful?