Sorting a set of values

Question:

I have values like this:

x = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
y = set(['4.918859000', '0.060758000', '4.917336999', '0.003949999', '0.013945000', '10.281522000', '0.025082999'])  

I want to sort the values in each set in increasing order. I don’t want to sort between the sets, but the values in each set.

Asked By: Justin Carrey

||

Answers:

From a comment:

I want to sort each set.

That’s easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That’s because the whole point of a set, both in mathematics and in almost every programming language,* is that it’s not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don’t really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Answered By: abarnert

Another method is to explicitly convert the set into a list (using list() function) and sort the list.

s = {10, 39, 3}

s_list = list(s)
s_list.sort()    # sort in-place
# [3, 10, 39]

Since Python 3.7, dicts keep insertion order. So if you want to order a set but still want to be able to do membership checks in constant time, you can create a dictionary from the sorted list using dict.fromkeys() (the values are None by default).

s = {10, 39, 3}

s_sorted = dict.fromkeys(sorted(s))               # ascending order
# {3: None, 10: None, 39: None}

s_sorted = dict.fromkeys(sorted(s, reverse=True)) # descending order
# {39: None, 10: None, 3: None}
Answered By: cottontail
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.