Home > OS >  sorting a set of tuples based on second value of tuple in python
sorting a set of tuples based on second value of tuple in python

Time:02-14

Hi I am new to python and wanted to sort these values based on the numeric values present in each tuple

b={('shoe',0.98),('bag',0.67),('leather',0.77)}

I have tried changing it into a list but then the tuple elements cannot be changed Thanks in advance

CodePudding user response:

Python sets are unordered, so you can’t sort them. But you can sort the elements in a set using the sorted function and passing a lambda that selects the second item of a tuple (since the set elements are tuples and you want to sort by the second elements of the tuples) to the key parameter. This returns a list:

out = sorted(b, key=lambda x:x[1])

Output:

[('bag', 0.67), ('leather', 0.77), ('shoe', 0.98)]

CodePudding user response:

Or you can use operator.itemgetter (there is also attrgetter):

from operator import itemgetter

out = sorted(b, key=itemgetter(1))
  • Related