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]) |
Sorted dictionary using sorted() and keys() is : a : 1 b : 2 c : 3 d : 4
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) |
Sorted dictionary using sorted() and items() is : 1 two 2 three 3 four 4 five
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) |
Sorted dictionary is : ['a', 'b', 'c', 'd']
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 ]) |
Sorted dictionary is : black :: #000000 green :: #008000 red :: #FF0000 white :: #FFFFFF
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) |
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 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 )) |
Sorted dictionary is : {"a": 1, "b": 2, "c": 3, "d": 4}
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) |
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) |
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})
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) |
{'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]) |
Sorted dictionary is : d : 4 c : 3 b : 2 a : 1
Please Login to comment...