127. Custom Sorting Functions
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
cmp_to_key7. 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
Last updated