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

Veröffentlicht am: 25 Dezember 2023
auf dem Kanal: sumit kumar
82
4

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)


Auf dieser Seite können Sie das Online-Video Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Bubble Sort mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer sumit kumar 25 Dezember 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 82 Mal angesehen und es wurde von 4 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!