A dictionary in Python is a large structure that is, by default, unordered. So, to make queries easier, you should sort dictionaries by key or value. But it’s never easy. So, let’s learn together. To sort a dictionary by its values in Python, we always use the sorted() function. Here's an example.
My_dict.items() gives a list of key-value pairs in this example, and the key=lambda item: item[1] indicates that the sorting should be based on the values (item[1]). The output is a sorted list of tuples that is then turned back into a dictionary using dict().
The output will look like {'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}. However, this sorts the dictionary by values in ascending order. Want to sort in descending order? Try incorporating the reverse=True model in the sorted() function.
Then the output will look like this:
{'orange': 8, 'apple': 5, 'banana': 2, 'grape': 1}
Check out more about Python programming in our blogs!