×

Sort Dictionary in Python

Dictionaries

In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value.

Dictionary contains key: value pair that provides which makes it more optimized. 

A dictionary is defined with a comma-separated list of Key-Value pairs enclosed with curly braces {}. Keys and values are separated with a colon (:) between other keys and values in the dictionary.

Need for sorting the dictionary

When the amount of data is too large, it is very difficult to handle the large data quickly and effectively. Sorting can remove the problem of handling a large amount of data. Sorting can reduce the complexity of data collection.

In Python, we can sort a dictionary by Keys and Values.

Sorting Dictionary by Key in Python

When a dictionary is sorted by key, it returns a list that contains tuples of key-value pairs. For example, {"b": 5, "c": 4, "a": 6} returns [("a", 6), ("b", 5), ("c", 4)].

We can perform sorting with only the sorted() function and also we can do it with for loop, lambda function, and dict.items() method.

Syntax:

sorted(iterable, key, reverse)

Here, we are using dict.items() with sorted() method for sorting a dictionary. It gives a list of tuples sorted by a key.

Example 1: Using dict.items()

A dictionary can be sorted by using dict.items() method. The dictionary is ordered for the sorted() method and then performs sorting with dict.items() method. 

# Code to sort a dictionary by key

# using dict.items()

from collections import OrderedDict

dict = {'ramesh':'30','Akash':'10,'sanjay':'20','Umesh':'40','deepak':'50'}

dict1 = OrderedDict(sorted(dict.items()))

print(dict1)

Output:

OrderedDict([('Akash', '10'), ('Umesh', '40'), ('deepak', '50'), ('ramesh', '30'), ('sanjay', '20')])

Example 2: Using for Loop

The dictionary sorting using keys can also be done by using for loop and keys() method. The keys() method separates the keys from the dictionary and sorting can be done by using for loop. 

# Code to sort a dictionary by key

# using for loop

from collections import OrderedDict

dictionary = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}

sorted_keys = sorted(dictionary.keys())

sorted_dict = {key:dictionary[key] for key in sorted_keys}

print(sorted_dict)

Output:

{'Rose': '22', 'Elice': '3', 'Jhon': '33', 'Ronny': '56', 'Rushel': '34'}

Example 3: Using sorted() method

By using the sorted() method, we can also sort a dictionary. The sorted() method is utilized for the given dictionary and it will be sort using for loop.

The sorted() method is used to perform the sorting operation. It allows three parameters: the iterable, the key, and the reverse.

# Code to sort a dictionary by key

# using sorted()

from collections import OrderedDict

dictionary = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}

dictionary1 = sorted(dictionary)

sorted_dict = {key:dictionary[key] for key in dictionary1}

print(sorted_dict)

Output:

{'Ronny': '56', 'Rose': '22', 'Elice': '3', 'Jhon': '33', 'Rushel': '34'}

Sort Dictionary By Value

As we sorted the dictionary with keys, similarly we can perform sorting with the values in the dictionary by using multiple methods. If we sort a dictionary with the values it returns a sorted dictionary.

We can perform sorting with only the sorted() function and also we can do it with for loop, lambda function, and dictionary.items() method.

Example 1: Using for loop

The dictionary sorting using keys can also be done by using for loop and sorted() method. In this method, values of the dictionary are ordered using the sorted() function and then find the keys of every value with for loop.

# Code to sort a dictionary by value

# using for loop

from collections import OrderedDict

dic = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}

print("Given dictionary : ",dic)

sorted_values = sorted(dic.values())

# Sort the values

sorted_dict = {}

for i in sorted_values:

    for k in dic.keys():

        if dic[k] == i:

            sorted_dict[k] = dic[k]

            break

#printing sorted dictionary

print("Sorted dictionary : ",sorted_dict)

Output:

Given dictionary : {'Ronny': '56', 'Jhon': '33', 'Elice': '3', 'Rose': '22', 'Rushel': '34'}

Sorted dictionary : {'Rushel': '34', 'Jhon': '33', 'Elice': '3', 'Ronny': '56', 'Rose': '22'}

Example 2: Using dictionary.items() Method

A dictionary can be sorted by using dictionary.items() method. The dictionary is ordered for the sorted() method and then performs sorting by values with dictionary.items() method. 

# Code to sort a dictionary by value

# using dictionary.items()

from operator import itemgetter

#given dictionary

dictionary = {'ramesh':'30','Akash':'10','sanjay':'20','Umesh':'40','deepak':'50'}

print("Given Dictionary: ", dictionary)

sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1)))

#printing sorted dictionary

print("Sorted Dictionary : ", sort_dict)

Output:

Given Dictionary: {'deepak': '50', 'ramesh': '30', 'sanjay': '20', 'Umesh': '40', 'Akash': '10'}

Sorted Dictionary : {'ramesh': '30', 'Akash': '10', 'Umesh': '40', 'deepak': '50', 'sanjay': '20'}

Example 3: Using lambda function

Lambda function and sorted() method can also be used together for sorting a dictionary by value in a predefined order in Python. An anonymous function is created by the lambda function that optimizes the code.

# Code to sort a dictionary by value

# using lambda function

dictionary = {'ramesh':'1','Akash':'3','sanjay':'5','Umesh':'4','deepak':'2'}

print("Given Dictionary: ", dictionary)

sort_dictionary= dict(sorted(dictionary.items(), key=lambda item: item[1], reverse = True))

print("Sorted Dictionary : ", sort_dictionary)

Output:

Given Dictionary: {'ramesh': '1', 'Umesh': '4', 'deepak': '2', 'sanjay': '5', 'Akash': '3'}

Sorted Dictionary : {'sanjay': '5', 'ramesh': '1', 'Umesh': '4', 'deepak': '2', 'Akash': '3'}

Conclusion

In this article, We have learned how to perform the sorting of dictionaries in Python. We have seen the different methods of sorting above and understood the use of sorting methods in Python.


Related Topics

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.