sort by second value in Python

Basic syntax of .sort() and sorted():

# array
array.sort(key=..., reverse=...)
new_array = sorted(array, key=..., reverse=...)

# tuple of list
tuples.sort(key=lambda x: x[1], reverse=...)
new_tuples = sorted(tuples, key=lambda x: x[1], reverse=...)

How to sort a list of tuples by the second value in Python? a list of array can also use this method.

tuples = [(10, 2), (11, 5), (5, 3), (6, 4)]

tuples.sort(key=lambda x: x[1])

print(tuples)

# output
# [(10, 2), (5, 3), (6, 4), (11, 5)]

How to sort dictionary by value in Python? This is not useful, because dictionary can't do loop in order.

How to exchange key-value of dictionary in Python? Be cautious, if two item have same value then only one item will be kept.

Last updated

Was this helpful?