Python’s Sorted Function Unleashed: From Lists to Custom Objects, Sorting Made Simple

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()`.

  1. 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.
  2. 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)
  3. `iterable`: The iterable (e.g., list, tuple, dictionary keys) that you want to sort.
  4. `key`: An optional argument that allows you to specify a custom sorting key function.
  5. `reverse`: An optional boolean parameter to sort in descending order if set to `True`.

2. Sorting Lists with `sorted()`.

  1. Let’s start with the most common use case: sorting lists.

2.1 Example 1: Sorting a List of Numbers.

  1. 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.

  1. 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.

  1. To sort in descending order, set the `reverse` parameter to `True`.
  2. 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.

  1. The `key` parameter allows you to specify a custom sorting criterion using a function
  2. For instance, you can sort a list of strings by their length.
  3. Example: Sorting a List of Strings by Length.

    words = ["apple", "banana", "cherry", "date", "berry"]
    sorted_words_by_length = sorted(words, key=len)
    # Output: ['date', 'apple', 'berry', 'banana', 'cherry']

4. Sorting Dictionaries.

  1. Python’s `sorted()` function can also sort dictionaries based on their keys or values.

4.1 Example 1: Sorting a Dictionary by Keys.

  1. 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__":
  2. 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.

  1. 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))
    if __name__ == "__main__":
  2. Output.

    {'banana': 0.9, 'apple': 1.2, 'date': 2.0, 'cherry': 3.5}

5. Sorting Custom Objects.

  1. You can sort a list of custom objects by defining a custom `key` function.
  2. Example: Sorting Custom Objects.

    class Person:
        def __init__(self, name, age):
   = 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.age}")
    if __name__ == "__main__":

6. Conclusion.

  1. Python’s `sorted()` function is a versatile tool for sorting a wide range of data structures with ease.
  2. Whether you’re working with lists, dictionaries, or custom objects, the `sorted()` function can help you arrange your data to meet your specific requirements.
  3. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.