# Sort the elements in dictionary based on its values
# without adding duplicates
dict1 = **{1:1, 2:9, 3:4, 4:6}**
sorted_values = sorted(dict1.values()) # Sort the values
sorted_dict = {}
for i in sorted_values:
for k in dict1.keys():
if dict1[k] == i:
sorted_dict[k] = dict1[k]
break
print(sorted_dict)
Output : **{1: 1, 3: 4, 4: 6, 2: 9}**
# with adding duplicates
# Sort the elements in dictionary based on its values
dict1 = **{0:6, 1:1, 2:9, 3:4, 4:6}**
sorted_values = sorted(dict1.values()) # Sort the values
sorted_dict = {}
for i in sorted_values:
for k in dict1.keys():
if dict1[k] == i:
sorted_dict[k] = dict1[k]
break
print(sorted_dict)
Output :
{1: 1, 3: 4, 0: 6, 2: 9}
here 4:6 is not printing I have to print all values from dictionary even there are duplicates in a dictionary