Python is a feature-enriched programming language that includes many features and tools. One such feature is a dictionary that enables us to save data in a combination of key-value pairs.
A dictionary is a mutable (that can be changed) data structure that stores information as key-value pairs. A key is a unique identifier whereas a value is the data corresponding to that key.
In this write-up, we will discuss how to do a value-based dictionary sort in Python
How to Do a Value-Based Dictionary Sort in Python?
The dictionary is unordered by default; however, it can be sorted in a particular order. The dictionary can be sorted either by key or by value.
There are several methods to do a value-based dictionary sort in Python. Some of them are:
- With the help of Nested loops
- By the use of Sorted() Method
- Using itemgetter() Method
- By the use of dict.items() and sorted() Functions
- By the use of Loop With Sorted Function
- By the use of Lambda Function
Let’s discuss them one by one:
Method 1: Using Nested Loops To Do a Value-Based Dictionary Sort in Python
Nested loops can be used to iterate through the list elements, and the rest of the work is done using comparison and swapping.
Let’s see an example
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
marklist=list(markdict.items())
print(marklist)
Here:
- In the first line, a dictionary is initialized named “markdict”.
- In the 2nd line, we have used the list() method to convert the dictionary to a list. The keys and values can be retrieved using the .items() method.
- Finally, we have printed the list using the print method.
The data is converted to a list as shown below:
Now we will use nested loops to sort the values in our dictionary as shown below:
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
marklist=list(markdict.items())
a=len(marklist)
for i in range(a-1):
for j in range(i+1, a):
if marklist[i][1]>marklist[j][1]:
z=marklist[i]
marklist[i]=marklist[j]
marklist[j]=z
sortdict=dict(marklist)
print(sortdict)
In the above code:
- l = len(marklist) calculates the length of the marklist.
- The nested loop is used and the list is sorted in ascending order by comparing the entries and switching them.
- The outer loop iterates across the list from zero to one less than the marklist’s overall length.
- The inner loop iterates over the list from the next element after “i” to the last element.
- The if condition is comparing the marks of the two students. If the marks of the student at index i are greater than the marks of the students at index j, the positions of the two students will be swapped.
The above code displays the following output.
We used nested loops by taking a temporary variable z and sorted the values in the list.
Method 2: Using Sorted() Method To Do a Value-Based Dictionary Sort in Python
Python’s sorted() method returns a sorted list from the given iterable. Let’s do an example:
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
marklist=list(markdict.items())
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)
In the above code:
- The dictionary markdict is converted into a list of tuples using the items() method.
- The sorted() method is then used to sort the marklist. It takes 2 arguments, the iterable to be sorted and the key which determines the sorting.
- The lambda function is set as a key parameter that specifies that the sorting must be done based on the second element of each tuple.
- After sorting the list of tuples, it is now transformed back into a dictionary using the dict method.
- The print() method is used to display the sorted list.
The result of the above code is displayed below:
From the above screenshot, we can see that the sorted values are displayed.
Method 3: Using itemgetter() Method To Do a Value-Based Dictionary Sort in Python
The itemgetter() method in Python returns an object that can be called from its operant. To return sorted items in the dictionary, the itemgetter() method is combined with the sorted() function. Let’s do it with the help of an example:
import operator
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
marklist= sorted(markdict.items(), key=operator.itemgetter(1))
sortdict=dict(marklist)
print(sortdict)
In the above code:
- First, import the operator module which provides suitable methods for working with operators.
- After that, initialize a dictionary.
- Use the sorted method with 2 arguments. The first argument is markdict.items() which returns a list of tuples. The sorting key is specified using the second argument, which is a key parameter.
- The operator is .itemgetter(1) which determines that the second element of each tuple will be used to determine how the items are sorted.
- Now use the dict method to transform the sorted list of tuples into a dictionary
- At the end, print the sorted list.
The above code results in the following output:
Hence, the dictionary has been sorted as shown above:
Method 4: Using dict.items() and sorted() Functions To Do a Value-Based Dictionary Sort in Python
dict.items() and sorted() methods can be used simultaneously to sort the value-based list of elements.
Let’s see this with an example:
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
marklist=sorted((value, key) for (key,value) in markdict.items())
sortdict=dict([(a,z) for z,a in marklist])
print(sortdict)
In the above code:
- Items of the list are sorted using the sorted() method. Additionally, the generator expression is used to create a sequence of tuples.
- The [(a,z) for z,a in marklist] is a list comprehension method that creates a list of tuples where the first element is the student name and the second element is the marks.
- A tuple is transformed into a dictionary using the dict() method.
- The sorted dictionary is printed using the print method.
The result of the above code is as follows:
It can be seen that the dictionary is sorted with the use of dict.items() and sorted() methods.
Method 5: Using for Loop With Sorted Function To Do a Value-Based Dictionary Sort in Python
A control flow statement that is used to specify the iteration is called a “for” loop. To do a value-based dictionary sort in Python, a for loop along with a sorted() function is used. Let’s do this practically with the help of an example:
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
sorted_values = sorted(markdict.values())
sorted_dict = {}
for i in sorted_values:
for k in markdict.keys():
if markdict[k] == i:
sorted_dict[k] = markdict[k]
break
print(sorted_dict)
In the above code:
- The first 2 steps are the same as previously.
- An empty dictionary is created named sorted_dict.
- The inner loop iterates over the keys, and the outer loop iterates over the sorted values.
- The if condition checks that the marks associated with the current student name match the sorted value “i”.
- If there’s a match the student name and marks are added to the sorted dictionary. If they don’t match, the break statement ends.
The result is as follows:
It can be seen that the markdict dictionary has been sorted by value with the help of a for loop.
Method 6: Using Lambda Function To Do a Value-Based Dictionary Sort in Python
An anonymous function that needs only one expression and can accept many arguments is known as a lambda function. We can sort a dictionary by value in Python with the help of a lambda function as illustrated below:
markdict={"Henry":78, "Joseph": 54, "Mark": 82, "Austin": 39, "Peter":61}
sorted_tuples = sorted(markdict.items(), key=lambda item: item[1])
sorted_dict = {a: z for a,z in sorted_tuples}
print(sorted_dict)
In the above code:
- The first line is the same as the previous example.
- markdist.items() converts a dictionary to a tuple. The key parameter is specified to be lambda which takes the tuple’s second element and uses it to sort the data
- A dictionary comprehension is used to iterate through the sorted tuples. For each tuple, it extracts the key and value and adds it to the sorted list.
- The sorted dictionary is printed using the print method.
The output is shown below:
Conclusion
Dictionaries are key-value pairs that are unordered by default. We can use different methods such as nested loops, the Sorted() method, itemgetter() method, or the lambda function to sort a dictionary by value. We can also use a for loop along with a sorted() function to sort a dictionary by value. This article has explained multiple methods to do a value-based dictionary sort in Python.