Multiple data are stored in Python by using a tuple, list, and dictionary. When the data are stored in Python by key-value pair that works like an associative array of other programming language is called the dictionary. The value of the dictionary is mutable. The dictionary can be stored based on the value of the key or value or both key and value. The dictionary can be sorted by using a simple for loop, built-in functions, and module. Different ways to sort dictionary data have been explained in this tutorial.

Example-1: Using for Loop to sort a dictionary

Create a python file with the following script to sort a dictionary using nested for loops. Two types of sorting have been shown in the script. A dictionary of four items has been declared here. The student’s name has been stored in the key, and the obtained mark has been stored in the value. An empty dictionary object has been declared before sorting to store the data of the sorted dictionary. After printing the original dictionary values, the nested ‘for’ loops have used to sort the dictionary based on the values by comparing the values of the dictionary. Another nested ‘for’ loop has used to sort the dictionary based on the keys by comparing the dictionary’s keys.

# Declare a dictionary


marks = {‘Neha Ali’: 83, ‘Abir Hossain’: 98, ‘Jafar Iqbal’: 79, ‘Sakil Ahmed’: 65}

# Print the original values of the dictionary

print(“Original dictionary: n, marks)

# Sort the values of the dictionary


sort_values = sorted(marks.values())


sorted_marks = {}

# Create the sorted dictionary based on values

for i in sort_values:


    for k in marks.keys():


        if marks[k] == i:


            sorted_marks[k] = marks[k]


            break

# Print the sorted dictionary

print(“Sorted dictionary based on the values: n, sorted_marks)

# Sort the keys of the dictionary


sort_keys = sorted(marks.keys())


sorted_keys = {}

# Create the sorted dictionary based on keys

for i in sort_keys:


    for k in marks:


        if k == i:


            sorted_keys[i] = marks[k]


            break

# Print the sorted dictionary

print(“Sorted dictionary based on the keys: n, sorted_keys)

Output:

The following output will appear after executing the above script. The original dictionary, the sorted dictionary based on the values, and the sorted dictionary based on the keys have shown in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/1-14.png" data-lazy- height="572" src="data:image/svg xml,” width=”928″>

Example-2: Using sorted() function with lambda

Using sorted() function with lambda is another way to sort a dictionary. Create a python file with the following script to sort a dictionary using the sorted() function and the lambda. A dictionary of four items has been declared in the script. The sorting type can be set by using lambda. The index position has been set to 1 in the third argument of the sorted() function. That means the dictionary will be sorted based on the values.

# Declare a dictionary


marks = {‘Neha Ali’: 83, ‘Abir Hossain’: 98, ‘Jafar Iqbal’: 79, ‘Sakil Ahmed’: 65}

# Print the original values of the dictionary

print(“Original dictionary: n, marks)

# Sort the dictionary based on marks using lambda


sorted_marks = sorted(marks.items(), key=lambda x: x[1])

print(“Sorted dictionary based on the marks: n, sorted_marks)

Output:

The following output will appear after executing the above script. The original dictionary, the sorted dictionary based on the values have shown in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/2-13.png" data-lazy- height="500" src="data:image/svg xml,” width=”927″>

Example-3: Using sorted() function with items()

Using sorted() function with items() function is another way to sort a dictionary, and it sorts the dictionary in ascending order based on keys by default. You can set the value of the reverse to True if you want the sorting in descending order. Create a python file with the following script to sort a dictionary using the sorted() function and the items(). The item() function is used to retrieve the keys or values from the dictionary. The sorted() function has used inside the dict() function to get a sorted dictionary as the output.

# Declare a dictionary


marks = {‘Neha Ali’: 83, ‘Abir Hossain’: 98, ‘Jafar Iqbal’: 79, ‘Sakil Ahmed’: 65}

# Print the original values of the dictionary

print(“Original dictionary: n, marks)

# Sort the dictionary based on names using dict() and sorted()


sorted_marks = dict(sorted((key, value) for (key, value) in marks.items()))

print(“Sorted dictionary based on the names: n, sorted_marks)

Output:

The following output will appear after executing the above script. The original dictionary, the sorted dictionary based on the keys as shown in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/3-13.png" data-lazy- height="571" src="data:image/svg xml,” width=”927″>

Example-4: Using sorted() function with itemgetter() function

Using sorted() function with itemgetter() function is another way to sort a dictionary. It also sorts the dictionary in ascending order by default. The itemgetter() function is under the operator module. Create a python file with the following script to sort a dictionary using the sorted() function and the itemgetter() function. You can set the sorting type using the itemgetter() function like the lambda. According to the following script, the dictionary will be sorted based on the values because 1 has passed as the argument value of the itemgetter() function.

# Import operator module

import operator

# Declare a dictionary


marks = {‘Neha Ali’: 83, ‘Abir Hossain’: 98, ‘Jafar Iqbal’: 79, ‘Sakil Ahmed’: 65}

# Print the original values of the dictionary

print(“Original dictionary: n, marks)

# Sort the dictionary based on marks using itemgetter()


sorted_marks = sorted(marks.items(), key=operator.itemgetter(1))

# Print the sorted dictionary

print(“Sorted dictionary based on the marks: n, dict(sorted_marks))

Output:

The following output will appear after executing the above script. The original dictionary, the sorted dictionary based on the values have shown in the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/4-13.png" data-lazy- height="543" src="data:image/svg xml,” width=”931″>

Conclusion:

A dictionary can be sorted with or without using the built-in function of Python. Four different ways to sort a dictionary have been explained in this tutorial by using various types of functions. The sorted() function is the main function to sort a dictionary. The order of the sorting can also be set by this function. Another function or index is used to sort the data based on the keys or values by mentioning the argument or the index value.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/07/echo/channel-logo-150×150.jpg60ef0824116a3.jpg" height="112" src="data:image/svg xml,” width=”112″>

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.