How do you sort a dictionary by its values in Python?
How do you sort a dictionary by its values in Python?
23826-Jun-2023
Updated on 27-Jun-2023
Home / DeveloperSection / Forums / How do you sort a dictionary by its values in Python?
How do you sort a dictionary by its values in Python?
Aryan Kumar
27-Jun-2023There are a few ways to sort a dictionary by its values in Python. Here are two of the most common methods:
Using the
sorted()
functionThe
sorted()
function can be used to sort any iterable object, including dictionaries. To sort a dictionary by its values, you would simply pass the dictionary to thesorted()
function and specify thekey
argument. Thekey
argument takes a function as its input, and the function will be used to determine the order of the elements in the iterable. In this case, you would pass a lambda function to thekey
argument. The lambda function would simply return the value of each key-value pair in the dictionary.For example, the following code sorts a dictionary by its values:
Python
This code will print the following output:
Code snippet
Using the
items()
methodThe
items()
method returns a list of key-value pairs from a dictionary. You can then use thesorted()
function to sort the list of key-value pairs by their values.For example, the following code sorts a dictionary by its values using the
items()
method:Python
This code will print the same output as the previous example.
Which method you use to sort a dictionary by its values will depend on your specific needs. If you need to sort the dictionary in place, then you will need to use the
sorted()
function with thekey
argument. If you do not need to sort the dictionary in place, then you can use theitems()
method and thesorted()
function.