I have created an SQLite database which has a table which stores temperature values. The temperature values are written to the database in ascending order for the first time. Then I read the temperature values from the database into a list and then add that list to a combo box to select temperatures. It works fine.
The resulting list is, say:
templist = ['25', '50', '100', '150', '200', '250', '300'].
Then I add a new temperature value, say, ’33’ to the database.
It gets appended to the end of the table. If I read the temperatures now, the list will become:
['25', '50', '100', '150', '200', '250', '300', '33'].
If I do templist.sort() or sorted(templist), the end result is
['150', '200', '25', '250', '300', '33', '50']
Is there a simple way to sort the list in ascending order, so that I get the following?
['25', '33', '50', '100', '150', '200', '250', '300']
The recommended approach in this case is to sort the data in the database, adding an
ORDER BYat the end of the query that fetches the results. Something like this:If for some reason that is not an option, you can change the sorting order like this in Python:
As has been pointed in the comments, the
intkey (orfloatif values with decimals are being stored) is required for correctly sorting the data if the data received is of typestring, but it’d be very strange to store temperature values as strings. If that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.