Sunday, November 17, 2024
Google search engine
HomeLanguagesDifferent ways of sorting Dictionary by Keys and Reverse sorting by keys

Different ways of sorting Dictionary by Keys and Reverse sorting by keys

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])


Output

Sorted 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)


Output

Sorted 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)


Output

Sorted 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])


Output

Sorted 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)


Output

Sorted 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))


Output

Sorted 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)


Output

OrderedDict([('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])


Output

Sorted 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.

RELATED ARTICLES

Most Popular

Recent Comments