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

Опубликовано: 25 Декабрь 2023
на канале: 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)


На этой странице сайта вы можете посмотреть видео онлайн Python Interview Question: Sort the dictionary by values in ascending order |Dictionary|Bubble Sort длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь sumit kumar 25 Декабрь 2023, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 82 раз и оно понравилось 4 зрителям. Приятного просмотра!