How do you sort a dictionary by its values in Python?
How do you sort a dictionary by its values in Python?
425
26-Jun-2023
Updated on 27-Jun-2023
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 thekeyargument. Thekeyargument 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 thekeyargument. 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 thekeyargument. If you do not need to sort the dictionary in place, then you can use theitems()method and thesorted()function.