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.
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)
#expected o/p {'date': 1, 'banana': 2, 'apple': 5, 'cherry': 8}
fruits_sorted={}
while fruits:
min_item=min(fruits.items(),key=lambda x:x[1])
fruits_sorted[min_item[0]]=min_item[1]
del fruits[min_item[0]]
Given dictionary
my_dict = {'apple': 5, 'banana': 2, 'cherry': 8, 'date': 1}
Custom sorting without using sorted()
def sort_dict_by_values_ascending(d):
items = list(d.items())
n = len(items)
for i in range(n - 1):
for j in range(0, n - i - 1):
if items[j][1] gt items[j + 1][1]:
Swap the elements if they are out of order
items[j], items[j + 1] = items[j + 1], items[j]
sorted_dict = dict(items)
return sorted_dict
sorted_dict = sort_dict_by_values_ascending(my_dict)
print(sorted_dict)
Sur cette page du site, vous pouvez voir la vidéo en ligne Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Bubble Sort durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur sumit kumar 25 décembre 2023, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 82 fois et il a aimé 4 téléspectateurs. Bon visionnage!