127. Custom Sorting Functions

In Python, custom sorting of complex data structures can be achieved by using the sorted() function or the sort() method with a custom comparison function. Python’s sorting mechanism is based on the key parameter, which is a function that transforms the items before sorting. Here's a series of examples that demonstrate how to use custom sorting functions to sort complex data structures:

1. Sorting List of Tuples by Second Element

data = [(1, 'apple'), (3, 'orange'), (2, 'banana')]

# Sorting by the second element of each tuple
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # Output: [(1, 'apple'), (2, 'banana'), (3, 'orange')]

2. Sorting a List of Dictionaries by Multiple Keys

data = [
    {'name': 'John', 'age': 25, 'city': 'New York'},
    {'name': 'Jane', 'age': 22, 'city': 'Los Angeles'},
    {'name': 'Alice', 'age': 30, 'city': 'Chicago'}
]

# Sorting by age, then by name
sorted_data = sorted(data, key=lambda x: (x['age'], x['name']))
print(sorted_data)
# Output: [{'name': 'Jane', 'age': 22, 'city': 'Los Angeles'}, {'name': 'John', 'age': 25, 'city': 'New York'}, {'name': 'Alice', 'age': 30, 'city': 'Chicago'}]

3. Sorting Objects by Multiple Attributes


4. Sorting Strings by Length


5. Sorting List of Tuples in Descending Order


6. Sorting with a Custom Comparison Function Using cmp_to_key

In Python 3, cmp functions have been removed. However, you can still use them with functools.cmp_to_key.


7. Sorting List of Dictionaries by String Length


8. Sorting Dates in a List of Tuples


9. Sorting List of Mixed Types (Integers and Strings)


10. Custom Sorting with Tuple and Custom Comparator


These examples show how to sort complex data structures using custom sorting logic, such as by multiple keys, object attributes, string lengths, or through custom comparison functions. By leveraging Python's sorted() function and key parameter, you can easily sort data based on a variety of criteria without writing complex sorting algorithms from scratch.

Last updated