Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Last Updated :
15 Jul, 2025
Prerequisite: Dictionaries in Python
A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and also reverse sorting by keys.
Using sorted() and keys():
keys() method returns a view object that displays a list of all the keys in the dictionary. sorted() is used to sort the keys of the dictionary.
Examples:
Input:
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
Output:
a: 1
b: 2
c: 3
d: 4
Python3
# Initialising a dictionary
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
# Sorting dictionary
sorted_dict = my_dict.keys()
sorted_dict = sorted(sorted_dict)
# Printing sorted dictionary
print("Sorted dictionary using sorted() and keys() is : ")
for key in sorted_dict:
print(key,':', my_dict[key])
OutputSorted dictionary using sorted() and keys() is :
a : 1
b : 2
c : 3
d : 4
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Using sorted() and items():
items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary's (key, value) tuple pair. sorted() is used to sort the keys of the dictionary.
Examples:
Input:
my_dict = {2:'three', 1:'two', 4:'five', 3:'four'}
Output:
1 'two'
2 'three'
3 'Four'
4 'Five'
Python3
# Initialising dictionary
my_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'}
# Sorting dictionary
sorted_dict = sorted(my_dict.items())
# Printing sorted dictionary
print("Sorted dictionary using sorted() and items() is :")
for k, v in sorted_dict:
print(k, v)
OutputSorted dictionary using sorted() and items() is :
1 two
2 three
3 four
4 five
The time complexity of sorting a dictionary using sorted() and items() is O(n log n) where n is the number of elements in the dictionary.
The space complexity is O(n) which is required for storing the sorted items.
Using sorted() and keys() in single line:
Here, we use both sorted() and keys() in a single line.
Examples:
Input:
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
Output:
Sorted dictionary is : ['a','b','c','d']
Python3
# Initialising a dictionary
my_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}
# Sorting dictionary
sorted_dict = sorted(my_dict.keys())
# Printing sorted dictionary
print("Sorted dictionary is : ", sorted_dict)
OutputSorted dictionary is : ['a', 'b', 'c', 'd']
The time complexity of sorting a dictionary will depend on the algorithm used. Generally, the time complexity of sorting a dictionary is O(n log n) where n is the number of items in the dictionary.
The space complexity is also O(n).
Using sorted() and items() in single line
Here, we use both sorted() and items() in a single line.
Examples:
Input:
my_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'}
Output:
Sorted dictionary is :
black :: #000000
green :: #008000
red :: #FF0000
white :: #FFFFFF
Python3
# Initialising a dictionary
my_dict = {'red': '#FF0000', 'green': '#008000',
'black': '#000000', 'white': '#FFFFFF'}
# Sorting dictionary in one line
sorted_dict = dict(sorted(my_dict .items()))
# Printing sorted dictionary
print("Sorted dictionary is : ")
for elem in sorted(sorted_dict.items()):
print(elem[0], " ::", elem[1])
OutputSorted dictionary is :
black :: #000000
green :: #008000
red :: #FF0000
white :: #FFFFFF
The time complexity of sorting a dictionary in one line is O(n log n), where n is the number of elements in the dictionary.
The space complexity is O(1).
Using a lambda function
The lambda function returns the key(0th element) for a specific item tuple, When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary.
Examples:
Input:
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
Output:
Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}
Python3
# Initialising a dictionary
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
# Sorting dictionary using lambda function
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
# Printing sorted dictionary
print("Sorted dictionary using lambda is : ", sorted_dict)
OutputSorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}
Time complexity: O(nlogn) where n is the number of elements in the dictionary.
Auxiliary space: O(n) where n is the number of elements in the dictionary.
6. Using json :
Python doesn't allow sorting of a dictionary. But while converting the dictionary to a JSON, you can explicitly sort it so that the resulting JSON is sorted by keys. This is true for the multidimensional dictionary.
Examples:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
Sorted dictionary is : {"a": 1, "b": 2, "c": 3,"d":4}
Python3
# Importing json
import json
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting and printing in a single line
print("Sorted dictionary is : ", json.dumps(my_dict, sort_keys=True))
OutputSorted dictionary is : {"a": 1, "b": 2, "c": 3, "d": 4}
Time Complexity:
The time complexity of sorting a dictionary using json.dumps() is O(NlogN), where N is the number of elements in the dictionary. This is because the sorting algorithm used by json.dumps() is a comparison-based sorting algorithm, which requires O(NlogN) time to sort N elements.
Space Complexity:
The space complexity of sorting a dictionary using json.dumps() is O(N), where N is the number of elements in the dictionary. This is because the sorting algorithm used by json.dumps() does not require any additional space for sorting the elements.
Using pprint
The Python pprint module actually already sorts dictionaries by key. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.
Examples:
Input:
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output:
Sorted dictionary is :
{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
Python3
# Importing pprint
import pprint
# Initialising a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sorting and printing in a single line
print("Sorted dictionary is :")
pprint.pprint(my_dict)
Time Complexity: O(n log n)
The time complexity of the sorting algorithm used is O(n log n). This is because sorting algorithms such as quicksort and heapsort have a time complexity of O(n log n).
Space Complexity: O(1)
The space complexity of sorting a dictionary is O(1). This is because sorting a dictionary does not require any extra space and all the sorting operations are done in-place.
Using collections and OrderedDict
The OrderedDict is a standard library class, which is located in the collections module. OrderedDict maintains the orders of keys as inserted.
Examples:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}1}
Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Python
# Importing OrderedDict
from collections import OrderedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = OrderedDict(sorted(my_dict.items()))
# Printing sorted dictionary
print(sorted_dict)
OutputOrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Using sortedcontainers and SortedDict :
Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict is a sorted mutable mapping. Sorted dict inherits from dict to store items and maintains a sorted list of keys. For this, we need to install sortedcontainers.
sudo pip install sortedcontainers
Examples:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
{"a": 1, "b": 2, "c": 3,"d":4}
Python3
# Importing SortedDict
from sortedcontainers import SortedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = SortedDict(my_dict)
# Printing sorted dictionary
print(sorted_dict)
Output:
SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
Time complexity: O(nlogn) where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n) where n is the number of key-value pairs in the dictionary.
Using class and function
Examples:
Input:
{"b": 2, "c": 3, "a": 1,"d":4}
Output:
{"a": 1, "b": 2, "c": 3,"d":4}
Python3
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
# Initialising dictionary and calling class
my_dict = SortedDisplayDict({"b": 2, "c": 3, "a": 1,"d":4})
# Printing dictionary
print(my_dict)
Output{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Reverse sorting dictionary by keys
Examples:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
Sorted dictionary is :
['a','b','c','d']
Python3
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Reverse sorting a dictionary
sorted_dict = sorted(my_dict, reverse=True)
# Printing dictionary
print("Sorted dictionary is :")
for k in sorted_dict:
print(k,':',my_dict[k])
OutputSorted dictionary is :
d : 4
c : 3
b : 2
a : 1
The time complexity of this code is O(n log n), where n is the number of keys in the 'my_dict' dictionary.
The space complexity of this code is O(n), where n is the number of keys in the 'my_dict' dictionary.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem