> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/useful-knowledge-about-python/sort-by-second-value-in-python.md).

# sort by second value in Python

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

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

```python
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)]
```

```python
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.

```python
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'}
```
