Back to Browse

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

159 views
Dec 25, 2023
12:55

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)

Download

1 formats

Video Formats

360pmp417.2 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

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