Sorting List in Python
Tags: python, tutorial, beginners, webdev
Published: 2020-05-01 07:35:43

In Python, Sorting is systematically arranging the data as per the given criteria. These have a lot of applications and you will be studying this in-depth. 

Examples: 
*) Arranging student roll numbers in ascending order 
*) Displaying the products which have high sales etc

## Sorting lists

Let us start with a simple example of list sorting by numbers. We'll be using a built-in method under list `sort()` method to get a result. Syntax
```python
newlist.sort(optional parameters)
```


Below optional parameters
**Option Name** --  **Values**   --   **Default Value**
**reverse** :    --  True or False --   False
**key**        --    NA  --             len() method to sort on bases on length of string,custom user defined function can also be used  |

Sorting numbers in Ascending order
```python
a=[
    9,6,8,2,1,7,3
]
a.sort()
print(a)

#PYTHON OUTPUT
[1, 2, 3, 6, 7, 8, 9]
```
Sorting numbers in Descending order
```python
a=[
    9,6,8,2,1,7,3
]
a.sort(reverse=True)
print(a)

#PYTHON OUTPUT
[9, 8, 7, 6, 3, 2, 1]
```
Sorting years with `sort()` using user defined function
```python
def myfunc(e):
    return e

a=[
    2018,2015,2017,2000,2013,2011
]
a.sort(key=myfunc)

print(a)

#PYTHON OUTPUT
[2000, 2011, 2013, 2015, 2017, 2018]
```
Sorting names by alphabets
```python
names = [
'John','Nancy','Amber','Peter','Bane'
]
names.sort()
print(names)#prints names in alphabetical ascending order

names.sort(reverse=True)
print(names)#prints names in alphabetical descending order

#PYTHON OUTPUT
['Amber', 'Bane', 'John', 'Nancy', 'Peter']
['Peter', 'Nancy', 'John', 'Bane', 'Amber']
```

Note : `sort()` method only sorts on list and returns `None`. To sort on non-list array use `sorted()` method.

Sorting Tuples
--------------

Sorting using `sorted()` method
```python
d = (
5,2,6,1,9
)

print(sorted(d))
print(sorted(d,reverse=True))

#PYTHON OUTPUT
[1, 2, 5, 6, 9]
[9, 6, 5, 2, 1]
```
Sorting Dictionaries
--------------------

Sorting Keys of the dictionary Below we have created a dictionary which has names in key and value. To only order keys of dictionary use `d.keys()` method this will return keys of that dictionary. Calling `reverse=True` attribute inside `sorted()` method will return sorted list in reverse order.
```python
d={
0:'Amber',
1:'John',
2:'Kiran',
3:'Rakesh',
4:'Yogesh',
}

print(sorted(d.keys())) #This will order keys of dictionary in Ascending Order

print(sorted(d.keys(),reverse=True)) # Calling reverse attribute with value True will print the keys of dictionary in Descending Order

#PYTHON OUTPUT
[0, 1, 2, 3, 4]
[4, 3, 2, 1, 0]
```
Sorting Values in the dictionary Here we'll be using the same method as above except insisted on calling `d.keys()`. We'll call `d.values()` method which returns values of dictionary.
```python
d={
0:'Amber',
1:'John',
2:'Kiran',
3:'Rakesh',
4:'Yogesh',
}

print(sorted(d.values())) #This will order values of dictonary in Ascending Order

print(sorted(d.values(),reverse=True)) # Calling reverse attribute with value True will print the values of dictonary in Descending Order
```
Advance Dictionary Sorting
--------------------------

In reality, there will be many cases where dictionary is multi-dimensional and need the be order. So in this tutorial, we'll be covering most of the complex multi-dimensional dict and sort them in order. Sorting dictionary by user age.
```python
d = {
0 : {
    'username' : 'Jane154',
    'fname' : 'Jane',
    'age' : 22,
},
1 : {
    'username' : 'Humayun12',
    'fname' : 'Humayun',
    'age' : 16,
},
2 : {
    'username' : 'Rakesh45',
    'fname' : 'Rakesh',
    'age' : 29,
},
3 : {
    'username' : 'Kimmy123',
    'fname' : 'Kimmy',
    'age' : 12,
},
}

def sortByAge(e):
return e[1]['age']

print(sorted(d.items(),key=sortByAge))

print("\n\nSorting age in reverse order with tuple inside list \n\n")

print(sorted(d.items(),key=sortByAge,reverse=True))

print("\n\nSorting age in reverse order and this will return a dictionary \n")

print(dict(sorted(d.items(),key=sortByAge,reverse=True)))

#PYTHON OUTPUT
[(3, {'username': 'Kimmy123', 'fname': 'Kimmy', 'age': 12}), (1, {'username': 'Humayun12', 'fname': 'Humayun', 'age': 16}), (0, {'username': 'Jane154', 'fname': 'Jane', 'age': 22}), (2, {'username': 'Rakesh45', 'fname': 'Rakesh', 'age':29})]
```

Sorting age in reverse order
```python

[(2, {'username': 'Rakesh45', 'fname': 'Rakesh', 'age': 29}), (0, {'username':'Jane154', 'fname': 'Jane', 'age': 22}), (1, {'username': 'Humayun12', 'fname': 'Humayun', 'age': 16}), (3, {'username': 'Kimmy123', 'fname': 'Kimmy', 'age':12})]




{2: {'username': 'Rakesh45', 'fname': 'Rakesh', 'age': 29}, 0: {'username': 'Jane154', 'fname': 'Jane', 'age': 22}, 1: {'username': 'Humayun12', 'fname': 'Humayun', 'age': 16}, 3: {'username': 'Kimmy123', 'fname': 'Kimmy', 'age': 12}}  
```
Note: Dictionaries are unordered and unsorted collection on data. so like lists they don't have sort() method. But bypassing dictionary in `sorted()` method will return Tuple inside list in sorted order.

[click here](http://thecodelearners.com/sorting-in-python/) to read the complete article