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

01 Oct, 2020
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.
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 dictionarymy_dict = {'c':3, 'a':1, 'd':4, 'b':2}  # Sorting dictionarysorted_dict = my_dict.keys()sorted_dict = sorted(sorted_dict)  # Printing sorted dictionaryprint("Sorted dictionary using sorted() and keys() is : ")for key in sorted_dict:    print(key,':', my_dict[key])
Sorted dictionary using sorted() and keys() is : 
a : 1
b : 2
c : 3
d : 4

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 dictionarymy_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'}  # Sorting dictionarysorted_dict = sorted(my_dict.items())  # Printing sorted dictionaryprint("Sorted dictionary using sorted() and items() is :")for k, v in sorted_dict:    print(k, v)
Sorted dictionary using sorted() and items() is :
1 two
2 three
3 four
4 five

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 dictionarymy_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}# Sorting dictionarysorted_dict = sorted(my_dict.keys())  # Printing sorted dictionaryprint("Sorted dictionary is : ", sorted_dict)
Sorted dictionary is :  ['a', 'b', 'c', 'd']

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 dictionarymy_dict = {'red': '#FF0000', 'green': '#008000',           'black': '#000000', 'white': '#FFFFFF'}  # Sorting dictionary in one linesorted_dict = dict(sorted(my_dict .items()))  # Printing sorted dictionaryprint("Sorted dictionary is : ")for elem in sorted(sorted_dict.items()):    print(elem[0], " ::", elem[1])
Sorted dictionary is : 
black  :: #000000
green  :: #008000
red  :: #FF0000
white  :: #FFFFFF

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 dictionarymy_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}  # Sorting dictionary using lambda functionsorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))  # Printing sorted dictionaryprint("Sorted dictionary using lambda is : ", sorted_dict)
Sorted dictionary using lambda is :  {'e': 12, 'a': 23, 'g': 67, 45: 90}

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 jsonimport json  # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4}  # Sorting and printind in a single lineprint("Sorted dictionary is : ", json.dumps(my_dict, sort_keys=True))
Sorted dictionary is :  {"a": 1, "b": 2, "c": 3, "d": 4}

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 pprintimport pprint  # Initialising a dictionarymy_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}  # Sorting and printing in a single lineprint("Sorted dictionary is :")pprint.pprint(my_dict)
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 OrderedDictfrom collections import OrderedDict  # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4}  # Sorting dictionarysorted_dict = OrderedDict(sorted(my_dict.items()))  # Printing sorted dictionaryprint(sorted_dict)
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 SortedDictfrom sortedcontainers import SortedDict  # Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4}  # Sorting dictionarysorted_dict = SortedDict(my_dict)  # Printing sorted dictionaryprint(sorted_dict)
Output:
SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
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 classmy_dict = SortedDisplayDict({"b": 2, "c": 3, "a": 1,"d":4})  # Printing dictionaryprint(my_dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Examples:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}

Output:
Sorted dictionary is :
['a','b','c','d']
Python3
# Initialising a dictionarymy_dict = {"b": 2, "c": 3, "a": 1,"d":4}  # Reverse sorting a dictionarysorted_dict = sorted(my_dict, reverse=True)  # Printing dictionaryprint("Sorted dictionary is :")  for k in sorted_dict:  print(k,':',my_dict[k])
Sorted dictionary is :
d : 4
c : 3
b : 2
a : 1

python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function