How can I **python sort set** values?

How can I python sort set values?

I have two sets of 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 within each set in increasing order. However, I do not want to sort the sets themselves, only the values inside each set. How can I achieve this in Python?

Hey All!

Here is the answer to your question @sndhu.rani

To sort each set, you can use Python’s sorted() function. For any iterable, including a set, sorted(s) will return a list of elements sorted in ascending order. Here’s an example:

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

Output:

['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Just remember, sorted() returns a list, not a set, because sets don’t have any inherent order. If you want to sort these as numbers rather than strings, you’ll need to convert them to float during sorting. You can do that with the key parameter:

print(sorted(s, key=float))

Output:

['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

This method works great if you’re dealing with strings that represent numbers. But ideally, you should store the numbers as actual numeric values if possible.

Exactly, @emma-crepeau! When you’re working with strings that represent numbers and want them sorted numerically, you just need to use the key parameter in sorted(). Like Tom mentioned, you can convert those strings to floats to ensure they’re sorted by their numeric value, not lexicographically.

For example:

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

Output:

['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

Using key=float is a simple and effective way to sort those string numbers correctly. It works perfectly when you want a numerical sort instead of an alphabetical one.

Right! And if you’re simply looking to sort them as strings, it’s just as straightforward. The default behavior of sorted() is to sort elements lexicographically. So, if the elements in your set are already strings, sorted() will sort them alphabetically. Here’s how it looks:

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

Output:

['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

As you can see, when sorting strings, the order might not be what you expect numerically. If that’s fine for your use case, then this method works perfectly. But for numerical sorting, remember to use key=float.