Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Sorted

Pubblicato il: 23 dicembre 2023
sul canale di: sumit kumar
92
6

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)


In questa pagina del sito puoi guardare il video online Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Sorted della durata di ore minuti seconda in buona qualità , che l'utente ha caricato sumit kumar 23 dicembre 2023, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 92 volte e gli è piaciuto 6 spettatori. Buona visione!