Python Program to Sort a Dictionary by Value Ad Sponsored

ⓘ Sponsored by

In Python, dictionaries are unordered collections, so you cannot directly sort a dictionary. However, you can sort the items in a dictionary based on their keys or values, and create a new ordered dictionary from the sorted items.

Python Code :

The below Python program that sorts a dictionary by its values:

# Define a dictionary of player names and scores
players = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Dave': 95}

# Sort the dictionary by value and create a new dictionary
sorted_players = {k: v for k, v in sorted(players.items(), key=lambda item: item[1])}

# Print the sorted dictionary


{'Charlie': 78, 'Alice': 85, 'Bob': 92, 'Dave': 95}

In this program, we first define a dictionary called players that contains player names as keys and their scores as values.

We then sort the dictionary by its values using the sorted() function. The sorted() function returns a list of tuples that contain each key-value pair in the dictionary, sorted by the value. We use a lambda function as the key parameter to specify that we want to sort the dictionary by its values.

Finally, we create a new dictionary called sorted_players by iterating over the sorted list of tuples and converting them back into a dictionary using a dictionary comprehension.

Note that in Python, dictionaries are inherently unordered. The sorted dictionary created in this program is actually a new dictionary object that happens to contain the same key-value pairs as the original dictionary, but in a different order Ad Sponsored

ⓘ Sponsored by