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)]
tuples = [(10, 2), (11, 5), (5, 3), (6, 4)]

tuples2 = sorted(tuples, key=lambda x: x[1])

print(tuples2)

# 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.

d = {'a': 10, 'b': 1, 'c': 4}

sort_d = sorted(d.items(), key=lambda x: x[1])

print(sort_d)

# output
# [('b', 1), ('c', 4), ('a', 10)]

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

d = {'1': 'one', '2': 'two', '3': 'three'}

d_new = dict((v,k) for k,v in d.items())

print(d_new)

# output
# {'one': '1', 'two': '2', 'three': '3'}

Last updated