I have a table selection, so a list of rows of column data. list[dict[str, str]]
The keys in each dictionary are just the column names that map to the row’s data.
Now in my app I want my users to be able to sort by any amount of columns with the ability to reverse some.
For example, imagine the following data:
data = [
{'name': "Bob", 'age': 15, 'height': 140},
{'name': "Bobby", 'age': 15, 'height': 178},
{'name': "Claire", 'age': 20, 'height': 165},
]
Now the user wants to primarly sort by age and secondarly by name in reverse.
My current solution is something similar to this:
def get_sort_key(*columns: tuple[str, bool]):
def key(row: dict[str, str]):
tuple(
tuple(
ord(c) * (-1 if reverse else 1)
for c in
row[col]
)
for col, reverse in columns
)
return key
But I recently realized that in my case above, “Bob” would still by sorted before “Bobby”, because “Bob” is the same string as “Bobby” up to the point it ends and therefore “Bob” < “Bobby” in any order.
A solution would be to pad the codepoints with -1 (or +1 in reverse) for the maximum expected string length, but I feel like there should be a way easier solution for my problem.
EDIT:
Assume all values are stringified before the the data is put into a sorting function!