A dictionary data type in Python stores data in key & value pairs. By default, the key:value pairs are not ordered. Python language does not have any inbuilt method to sort the dictionary by its value. However there are a few workarounds to sort a dictionary in Python. Here is one of the methods using the function sorted().
In the below sample code, I’ve done sorting in both ascending order and descending order.
Code sample to sort a dictionary
# Sorting a dictionary by value
# Create a dictionary
my_dictinary = {1: 'Tiger', 2: 'Leopard', 3: 'Jaguar', 4: 'Panther', 5: 'Deer', 6: 'Bear'}
print("Original Dictionary:", "\n", my_dictinary, "\n")
# Sort the dictionary in ascending order
my_dictinary = dict(sorted(my_dictinary.items(), key=lambda x: x[1]))
print("Ascending Order:", "\n", my_dictinary, "\n")
# Sort the dictionary in descending order
my_dictinary = dict(sorted(my_dictinary.items(), key=lambda x: x[1], reverse=True))
print("Descending Order:", "\n", my_dictinary, "\n")
Reference
- More about sorted() at Python Docs.