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)
On this page of the site you can watch the video online Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Sorted with a duration of hours minute second in good quality, which was uploaded by the user sumit kumar 23 December 2023, share the link with friends and acquaintances, this video has already been watched 92 times on youtube and it was liked by 6 viewers. Enjoy your viewing!