Sort Dictionary by Value Python
Updated on Mar 28, 2025 | 7 min read | 5.6k views
Share:
For working professionals
For fresh graduates
More
Updated on Mar 28, 2025 | 7 min read | 5.6k views
Share:
Table of Contents
Python is a popular programming language that can be used to create web applications on a server. It can be used to develop workflows alongside the software. In addition to connecting database systems, Python can also read and manipulate files. The programs can be devised to perform complex problems of mathematics and handle big data. It enables a production-ready development of software and quick prototyping.
There are several primitive data types in Python, such as a dictionary, set, list, tuple etc. This popular programming language also encompasses collections modules with dedicated data structures such as deque, ChainMap etc. These data types contain functions that make the Python code more efficient and hence it is easy for the user to work with them. The dictionary data type in Python has one such predefined function called the sort function. Let us discuss the sorting of the Python dictionary by values.
The categorization or classification of data items in Python is referred to as data types. Several built-in data types are offered by Python. The Python built-in data types are mentioned below.
1. Scalar Data Type
Examples: int, float, bool, complex, none
2. Sequence data type
Examples: String, List and tuple
3. Mapping data type
Examples: Dictionary
4. Set data type
Examples: Set and frozenset
5. Mutable and immutable data types
Numbers, tuples and strings are immutable, whereas lists of dictionary objects are mutable.
A collection data type in Python that consists of pairs of key and value similar to a map in other programming languages such as Java is called the dictionary data type. Some of the important features of the dictionary data type are listed below.
Several operations that can be used in a Python dictionary are as follows.
Check Out upGrad’s Data Science Courses
Sorting of a dictionary in Python can be accomplished through various methods, as listed below.
Sorting dictionaries by values in Python can be accomplished through various approaches.
Let us discuss all these approaches in detail in the subsequent sections.
Also, Check out all trending Python tutorial concepts in 2024.
A for Loop can be used to sort a dictionary by value in Python. The values of the dictionary are ordered with the sorted() function. The compiler then loops through the sorted values to determine the keys for each value. The key-value pairs are sorted in the same order to form a new dictionary. The dictionary cannot be reordered after sorting since the order pairs are written in an entirely new dictionary.
The sorted() function is used to sort the array values. While sorting a dictionary, the sorted() function accepts one or more parameter in the following syntax.
sorted(dict1, key=dict1.get)
In the above code statement, the ‘key’ is the function that is invoked on each element before comparing the values for sorting. The value for a key in the dictionary is returned by the get() method on the objects of the dictionary. The expression “sorted(dict1, key=dict1.get)” will revert a key’s list for which the values are sorted in a specified order. A new dictionary that is sorted can be created with this.
The sorted() function reduces the code size. When combined with the itemgetter() function, the sorted() function provides a more concise solution to sort a dictionary by value in Python.
The itemgetter() function is included in the module ‘operator’. This function reverts a callable object that can return an element from an object. A callable object that reverts any dictionary value with ‘2’ as its key is created with the itemgetter() function in the example below.
The items() method can be accessed by every dictionary. The key-value pairs are returned as a list of tuples by this method. The itemgetter() method can be used to sort the tuples’ list by pulling the tuple’s second value. Once the tuples list is sorted, a new dictionary can be created with those values.
The nameless or anonymous functions in Python are referred to as the Lambda functions. The use of the lambda function eliminates the need of importing the
The methods discussed till now are compatible only with Python 3.7 and other higher versions. However, the next method that will be discussed is compatible with the earlier versions too.
The collections module contains the OrderedDict() function that can be used to retain the sorted dictionary. This can be used once the dictionary is sorted by values.
Using the ‘sorted()’ Method and Lambda Function to Sort a Dictionary by means of Value
A lambda feature in aggregate with the sorted() approach is one way to sort dictionary by value Python. By using this technique, a clean listing of tuples that incorporate a key-cost pair from the authentic dictionary is created. The sorted() function sorts the listing of tuples by means of the usage of the value, that is, the second element in each tuple. After that, a brand new dictionary can be made using the sorted list of tuples.
Consider the subsequent example to know a way to use a lambda function and the sorted() function to order strings in a dictionary by means of value.
my_dict = “orange”: “orange”, “apple”: “red”, and “banana”: “yellow.”
The following code is for sorting the dictionary with the aid of cost:
The same as dict(sorted (my_dict.items(), key=lambda item: item[1]), and item[1]), sorted_dict is item[1].
This code generates a new dictionary with identical keys because the antique one but values ordered alphabetically:
“orange” is “orange,” “apple” is “red,” and “banana” is “yellow.”
Using the ‘sorted()’ Function and the ‘key’ Parameter because the Sorting Criterion
To type a dictionary by using value, the sorted() technique calls for a lambda function to be supplied as the key parameter. Each key-fee pair inside the dictionary has its value extracted via the lambda function. A new dictionary that is taken care of by fee may be made the usage of the value again through the sorted() function.
Using the ‘itemgetter()’ Method from the ‘operator’ Module
Utilising the operator module’s itemgetter() feature is any other method to find a dictionary by value. A lambda function is not as effective as this function. The item supplied to the callable object that the itemgetter() function creates is removed from its operand.
Using the ‘sorted()’ Function Along with a ‘Lambda Function’
By sorting the list based on the value of each tuple’s second element, this approach creates a list of tuples from the original dictionary key-value pairs.
If you are curious to learn about tableau, data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources