How to use function sorted in Python? - with practical example
Introduction:
In Python, the sorted() function is used to sort a list, tuple, or any iterable object. It returns a new sorted list without modifying the original data structure. The sorted() function takes an iterable as an argument and returns a sorted list.
Example 1:
Let's say we have a list of numbers that we want to sort in ascending order using the sorted() function.
Explaining:
1. Create a list of numbers that we want to sort.
2. Use the sorted() function to sort the list in ascending order.
3. Assign the sorted list to a new variable to store the sorted result.
4. Print the sorted list to see the sorted output.
Code:
Example 2: Now, let's sort a dictionary based on its keys in descending order using the sorted() function. Explaining: 1. Create a dictionary with key-value pairs. 2. Use the sorted() function with the dictionary's keys to sort the keys in descending order. 3. Iterate over the sorted keys and print the corresponding values from the dictionary. Code:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3] sorted_numbers = sorted(numbers) print(sorted_numbers)
Example 2: Now, let's sort a dictionary based on its keys in descending order using the sorted() function. Explaining: 1. Create a dictionary with key-value pairs. 2. Use the sorted() function with the dictionary's keys to sort the keys in descending order. 3. Iterate over the sorted keys and print the corresponding values from the dictionary. Code:
my_dict = {'b': 3, 'a': 1, 'c': 5, 'd': 2} sorted_keys = sorted(my_dict.keys(), reverse=True) for key in sorted_keys: print(f'{key}: {my_dict[key]}')
Comments
Post a Comment