All about

The sorted function is used in Python to sort iterable objects such as lists, tuples, and strings. This function returns a new sorted list without modifying the original data. The basic syntax of the sorted function is as follows

sorted(iterable, key=None, reverse=False)

 

iterable: Represents the iterable object to be sorted (e.g., a list, tuple, or string).

key (optional): A function that provides the sorting criterion. The default is None, in which case the elements are sorted based on their own values.

reverse (optional): The default is False, and if set to True, the sorting is done in descending order.

Here's a simple example to illustrate the usage of the sorted function.

# Sorting a list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

# Sorting a string
text = "python"
sorted_text = sorted(text)
print(sorted_text)  # Output: ['h', 'n', 'o', 'p', 't', 'y']

# Sorting in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

 

You can also use the key parameter to specify a custom sorting criterion. In this case, provide a function that returns the value to be used for sorting. For example, sorting based on the absolute values.

numbers = [-5, 3, -1, 8, -2, 7]
sorted_numbers_abs = sorted(numbers, key=abs)
print(sorted_numbers_abs)  # Output: [-1, -2, 3, -5, 7, 8]

 

For dictionary,

# Sorting a dictionary by its keys
my_dict = {'apple': 3, 'banana': 1, 'orange': 5, 'grape': 2}
sorted_dict_keys = dict(sorted(my_dict.items()))
print(sorted_dict_keys)
# Output: {'apple': 3, 'banana': 1, 'grape': 2, 'orange': 5}

# Sorting a dictionary by its values
sorted_dict_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict_values)
# Output: {'banana': 1, 'grape': 2, 'apple': 3, 'orange': 5}

 

In the first example, the dictionary is sorted based on its keys using the sorted function. In the second example, it is sorted based on the values using the key parameter with a lambda function.

 

For object attrubute,

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Creating a list of Person objects
people = [Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35)]

# Sorting the list of objects based on the 'age' attribute
sorted_people = sorted(people, key=lambda person: person.age)
for person in sorted_people:
    print(f"{person.name}: {person.age} years old")
# Output:
# Bob: 25 years old
# Alice: 30 years old
# Charlie: 35 years old

 

In this example, the sorted function is used to sort a list of Person objects based on the 'age' attribute. The key parameter is utilized with a lambda function that extracts the 'age' attribute for comparison.

 

Here's an example of a list containing dictionaries

# List with dictionaries
people_list = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'San Francisco'},
    {'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'}
]

# Sorting dictionaries based on 'age'
sorted_people = sorted(people_list, key=lambda person: person['age'])
for person in sorted_people:
    print(f"Name: {person['name']}, Age: {person['age']}, City: {person['city']}")

 

In this way, the sorted function can be used to sort various types of data.

 

ref. https://docs.python.org/3/howto/sorting.html

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading