Python is renowned for its versatility, and its extensive standard library offers a multitude of powerful tools for developers. Among these tools, the `sorted()` function stands out as a handy utility to sort iterable data structures with ease. Whether you’re working with lists, tuples, dictionaries, or custom objects, the `sorted()` function can help you arrange your data in a meaningful way. In this article, we’ll delve into the intricacies of using Python’s `sorted()` function with a range of examples to ensure you’re well-equipped to sort data effectively in your Python projects.
1. The Basics of `sorted()`.
- The `sorted()` function is a built-in Python function that takes an iterable as its primary argument and returns a sorted version of that iterable.
- It can sort elements in both ascending and descending order, depending on the optional `reverse` parameter. Here’s the basic syntax of the `sorted()` function:
sorted(iterable, key=None, reverse=False)
- `iterable`: The iterable (e.g., list, tuple, dictionary keys) that you want to sort.
- `key`: An optional argument that allows you to specify a custom sorting key function.
- `reverse`: An optional boolean parameter to sort in descending order if set to `True`.
2. Sorting Lists with `sorted()`.
- Let’s start with the most common use case: sorting lists.
2.1 Example 1: Sorting a List of Numbers.
- Source code.
numbers = [5, 1, 3, 2, 4] sorted_numbers = sorted(numbers) print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
2.2 Example 2: Sorting a List of Strings.
- Source code.
fruits = ["apple", "banana", "cherry", "date", "berry"] sorted_fruits = sorted(fruits) print(sorted_fruits) # Output: ['apple', 'banana', 'berry', 'cherry', 'date']
2.3 Sorting in Descending Order.
- To sort in descending order, set the `reverse` parameter to `True`.
- Example: Sorting a List in Descending Order.
numbers = [5, 1, 3, 2, 4] sorted_numbers_desc = sorted(numbers, reverse=True) print(sorted_numbers_desc) # Output: [5, 4, 3, 2, 1]
3. Custom Sorting with the `key` Parameter.
- The `key` parameter allows you to specify a custom sorting criterion using a function
- For instance, you can sort a list of strings by their length.
- Example: Sorting a List of Strings by Length.
words = ["apple", "banana", "cherry", "date", "berry"] sorted_words_by_length = sorted(words, key=len) print(sorted_words_by_length) # Output: ['date', 'apple', 'berry', 'banana', 'cherry']
4. Sorting Dictionaries.
- Python’s `sorted()` function can also sort dictionaries based on their keys or values.
4.1 Example 1: Sorting a Dictionary by Keys.
- Source code.
def sorted_dict_by_key(): fruit_prices = {"apple": 1.2, "cherry": 3.5, "banana": 0.9, "date": 2.0} sorted_fruit_prices = dict(sorted(fruit_prices.items())) print(sorted_fruit_prices) # Output: {'apple': 1.2, 'banana': 0.9, 'cherry': 3.5, 'date': 2.0} tmp_dict_items = fruit_prices.items() #sorted_dict_items = sorted(tmp_dict_items, key=lambda item:item[1]) sorted_dict_items = sorted(tmp_dict_items, reverse=True) sorted_fruit_prices = dict(sorted_dict_items) print(sorted_fruit_prices) # Output: {'date': 2.0, 'cherry': 3.5, 'banana': 0.9, 'apple': 1.2} if __name__ == "__main__": sorted_dict_by_key()
- Output.
{'apple': 1.2, 'banana': 0.9, 'cherry': 3.5, 'date': 2.0} {'date': 2.0, 'cherry': 3.5, 'banana': 0.9, 'apple': 1.2}
4.2 Example 2: Sorting a Dictionary by Values.
- Source code.
def sort_by_item_in_list(item): return item[1] def sorted_dict_by_value(): fruit_prices = {"apple": 1.2, "cherry": 3.5, "banana": 0.9, "date": 2.0} #sorted_fruit_prices_by_value = dict(sorted(fruit_prices.items(), key=lambda item: item[1])) sorted_fruit_prices_by_value = dict(sorted(fruit_prices.items(), key=sort_by_item_in_list)) print(sorted_fruit_prices_by_value) if __name__ == "__main__": sorted_dict_by_value()
- Output.
{'banana': 0.9, 'apple': 1.2, 'date': 2.0, 'cherry': 3.5}
5. Sorting Custom Objects.
- You can sort a list of custom objects by defining a custom `key` function.
- Example: Sorting Custom Objects.
class Person: def __init__(self, name, age): self.name = name self.age = age def sort_by_age(person): return person.age def sort_custom_object_list(): people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)] #sorted_people_by_age = sorted(people, key=lambda person: person.age) sorted_people_by_age = sorted(people, key=sort_by_age) for person in sorted_people_by_age: print(f"{person.name}: {person.age}") if __name__ == "__main__": sort_custom_object_list()
6. Conclusion.
- Python’s `sorted()` function is a versatile tool for sorting a wide range of data structures with ease.
- Whether you’re working with lists, dictionaries, or custom objects, the `sorted()` function can help you arrange your data to meet your specific requirements.
- By understanding its usage and experimenting with the provided examples, you can confidently incorporate this function into your Python projects, making your code more organized and efficient.