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