×

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 Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.