In Python, the sorted() function is used to sort iterable objects (e.g., lists, tuples, strings) and return a new sorted list. It does not modify the original iterable; instead, it creates a new sorted version of it. The sorted() function can also take optional arguments to customize the sorting behavior.
Here's how the sorted() function works with some examples:
Sorting a list of numbers in ascending order
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 (characters are sorted lexicographically)
text = "python"
sorted_text = sorted(text)
print(sorted_text)
Output: ['h', 'n', 'o', 'p', 't', 'y']
You can use the key parameter to specify a custom sorting criterion. The key should be a function that takes an element from the iterable and returns a value by which the elements are sorted
Sorting a list of strings by their length
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words)
Output: ['date', 'apple', 'banana', 'cherry']
Sorting a list of tuples by the second element of each tuple
pairs = [(1, 4), (2, 2), (3, 3), (4, 1)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
Output: [(4, 1), (2, 2), (3, 3), (1, 4)]
###code used in video:-
fruits = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 1}
Sort the dictionary by values in ascending order
fruits_sorted=dict(sorted(fruits.items(),key=lambda x:x[1]))
print(fruits_sorted)
Auf dieser Seite können Sie das Online-Video Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Sorted mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer sumit kumar 23 Dezember 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 92 Mal angesehen und es wurde von 6 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!