How to Sort Object Array In Python?

Python provides a built-in method called sort to sort an array. It provides an option to specify the order of the sort.

# Python3.8
# Sorting Array in Ascending Order
lst = [-1,200,1,100,50]
lst.sort()
print(lst)

# Output
# [-1, 1, 50, 100, 200]

Note: Sort method doesn’t return a new Array, instead it modifies the same.

To sort array in descending order you can specify reverse parameter to True.

# Python3.8
# Sorting Array in Descending Order
lst = [-1,200,1,100,50]
lst.sort(reverse=True)
print(lst)

# Output
# [200, 100, 50, 1, -1]

Sorting Object Array Using Python

Array might not always have numeric data. Most of the time for data coming from REST APIs, it will be object arrays. You can specify a function to the sort method to pick the value based on which the object needs to be sorted.

# Python3.8
# Sorting Object Array in Ascending Order

def customSort(k):
    return k['value']

lstObj = [{'value' : -1},{'value' : 200},{'value' : 1},{'value' : 100},{'value' : 50}]
lstObj.sort(key=customSort)
print(lstObj)

# Output
# [{'value': -1}, {'value': 1}, {'value': 50}, {'value': 100}, {'value': 200}]

As seen in the above code, customSort method has been passed as key to the sort method. Set the reverse parameter to True to sort Array object in descending order.

# Python3.8
# Sorting Object Array in Descending Order

def customSort(k):
    return k['value']

lstObj = [{'value' : -1},{'value' : 200},{'value' : 1},{'value' : 100},{'value' : 50}]
lstObj.sort(key=customSort, reverse=True)
print(lstObj)

# Output
# [{'value': 200}, {'value': 100}, {'value': 50}, {'value': 1}, {'value': -1}]