Sorting a dictionary by its values is a common task in Python programming. In this tutorial, we will explore multiple methods to achieve this and provide you with a solid understanding. By the end of this tutorial, you’ll be equipped with various techniques that you can leverage in your programming projects.
6 Ways to Sort Dictionary by Value in Python
Before we begin, let’s quickly review what a dictionary is in Python. A dictionary is an unordered collection of items, where each item consists of a key-value pair. Keys are unique, immutable, and used to access values associated with them. Here’s a quick example:
# Sample Dict
di_ct = {'apple': 5, 'banana': 2, 'orange': 8, 'kiwi': 3}
In the above dictionary, ‘apple’, ‘banana’, ‘orange’, and ‘kiwi’ are keys, and 5, 2, 8, and 3 are their respective values.
Must Read:
1. Python Dictionary to JSON
2. Python Append to Dictionary
3. Python Merge Dictionaries
4. Python Iterate Through a Dictionary
5. Python Search Keys by Value in a Dictionary
6. Python Multiple Ways to Loop Through a Dictionary
7. Python Insert a Key-Value Pair to the Dictionary
In Python, the sorting of arrays is achievable in many ways. Here, we’ll provide five such techniques to do this job. Firstly, check the sorted() method, one of Python’s built-in functions.
Sort Dictionary Using Lambda Function
The sorted()
function is a versatile tool for sorting iterable objects in Python. By default, it sorts dictionaries based on keys. However, we can utilize the key
parameter to specify sorting based on values. Here’s an example:
# Sort dict by values using sorted() and lambda function
new_dict = dict(sorted(di_ct.items(), key=lambda item: item[1]))
# Print the sorted dict
print(new_dict)
In this example, the key=lambda item: item[1]
lambda function extracts the values for sorting, resulting in a dictionary sorted by its values in ascending order.
Sort Dictionary Using ItemGetter()
The operator
module in Python provides a convenient itemgetter()
function for extracting values or elements from an iterable. This can be particularly useful when sorting dictionaries. Here’s an example:
from operator import itemgetter
# Sort dict by values using itemgetter()
new_dict = dict(sorted(di_ct.items(), key=itemgetter(1)))
# Print the sorted dict
print(new_dict)
Here, itemgetter(1)
is equivalent to the lambda function in the previous example, extracting values for sorting.
Use Sorted() with Custom Function
You can define a custom function to specify the sorting criteria for the dictionary. This offers flexibility for more complex sorting logic. Here’s an example.
# Custom func
def custom_sort(item):
return item[1]
# Sort dict by values using custom func
sorted_dict_val_custom = dict(sorted(di_ct.items(), key=custom_sort, reverse=True))
# Print the sorted dict
print(sorted_dict_val_custom)
In this example, the custom_sort
function returns the values, and the reverse=True
parameter sorts in descending order.
Sort Dictionary Using OrderedDict
The collections
module in Python provides the OrderedDict
class, which maintains the order of the keys. We will leverage this feature in the below example:
from collections import OrderedDict
# Sort dict by values using OrderedDict
sorted_dict_val_ord = OrderedDict(sorted(di_ct.items(), key=lambda item: item[1]))
# Print the sorted dict
print(sorted_dict_val_ord)
The OrderedDict
maintains the order of insertion, effectively resulting in a dictionary sorted by values.
Sort Using List Comprehension
You can use list comprehension to create a list of tuples and sort them using the sorted() function. Convert them back to a dictionary. Here’s an example.
# Sort dict by values using list comprehension and sorted()
sorted_dict_val_by_lc = dict(sorted([(k, v) for k, v in di_ct.items()], key=lambda item: item[1]))
# Print the sorted dict
print(sorted_dict_val_by_lc)
In this example, the list comprehension creates a list of tuples and sorted()
sorts them based on values. The resulting list is then converted back into a dictionary.
Sort Using Pandas DataFrame
We can even use Pandas data frame to sort the dictionary by values. Try this if you have a large amount of data and processing of this size could impact the performance. Here’s an example of how you can get the sorting done using Pandas:
import pandas as pds
# Create a Data Frame from the dict
dfr = pds.DataFrame(list(di_ct.items()), columns=['Fruit', 'Quantity'])
# Sort Data Frame by values
sorted_df = dfr.sort_values(by='Quantity').set_index('Fruit').to_dict()['Quantity']
# Print the sorted dict
print(sorted_df)
In this example, the pandas
library is used to create a data frame, which is then sorted by values, and the result is converted back into a dictionary.
Must Read: Pandas Series and DataFrame Explained in Python
Frequently Asked Questions
Go through the below FAQs addressing a few of the common concerns.
Q1: Can I sort a dictionary in descending order using these methods?
Answer: Yes! For methods using the sorted()
function, you can achieve descending order by specifying the reverse
parameter. For example:
# Sorting dictionary in descending order using sorted() and lambda function
sorted_dict_values_desc = dict(sorted(di_ct.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict_values_desc)
Q2: Is there a way to sort a dictionary in place?
Answer: The methods using sorted() do not modify the original object. If you want to sort it in place, you can use the collections.OrderedDict
method:
# Sorting dictionary in-place using OrderedDict
di_ct = OrderedDict(sorted(di_ct.items(), key=lambda item: item[1]))
print(my_dict)
Q3: Can I sort a dictionary with different data types?
Answer: Yes, the methods mentioned in the tutorial apply to dictionaries with any comparable data types. Python’s sorting functions can handle a variety of data types, making them versatile for different scenarios.
Q4: How do I sort a dictionary by keys instead of values?
Answer: By default, dictionaries are sorted by keys. If you want to explicitly sort by keys, you can use the sorted()
function without specifying the key
parameter:
# Sorting dictionary by keys
sorted_dict_keys = dict(sorted(di_ct.items()))
print(sorted_dict_keys)
Feel free to experiment with these methods and adapt them to your specific use cases.
Sorting dictionaries is a common operation. Having multiple methods at your disposal ensures you can choose the most suitable approach for your use case.
Happy Coding,
Team TechBeamers