Sort Python Dictionary by Value (Descending)

One way to sort a dictionary by values in descending order is by using the sorted() function and a lambda function, as shown below:

my_dict = {'a': 10, 'b': 5, 'c': 8, 'd': 12}

sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))

print(sorted_dict)

The output result is:

{'d': 12, 'a': 10, 'c': 8, 'b': 5}
bannerAds