In this article we will discuss how to sort the contents of dictionary by key or value.

Suppose we have a dictionary of string and ints i.e.

# Dictionary of strings and ints
wordsFreqDict = {
    "hello": 56,
    "at" : 23 ,
    "test" : 43,
    "this" : 43
    }

Dictionary is like a hash table that store the elements by calculating hashes of keys and orders of elements in it can not be predicted. Therefore, its also called unordered container and we can sort the dictionary in place. But we can create a either create a list of tuples (key value) pairs which is sorted or we can iterate over the contents of dictionary in sorted order.

Let’s see how to do sort the contents of dictionary in different ways,

Sort a dictionary contents by key

There are different ways to sort the elements of dictionary be keys i.e.

Sort Dictionary contents by keys using dict.keys()

dict.keys()

It returns a iterable view of all the keys in dictionary.

We can create a new sorted dictionary from this iterable sequence of keys i.e.

sorted(wordsFreqDict.keys())

Now we will iterate over this sorted list of keys and select each entry from dictionary i.e.
'''
 Iterate over a sorted list of keys and select value from dictionary for each key
 and print the key value pairs in sorted order of keys
'''
for key in sorted(wordsFreqDict.keys()) :
    print(key , " :: " , wordsFreqDict[key])

It will print the dictionary in a sorted order of keys i.e.
at  ::  23
hello  ::  56
test  ::  43
this  ::  43

Now we can achieve the same thing using an another function of dictionary i.e. items(). Its more efficient.

Sort Dictionary contents by keys using dict.items()

dict.items()

It returns an iterable sequence of tuples that contains all key value pairs in dictionary.
We can create a new sorted list of tuple by this iterable sequence i.e.
sorted(wordsFreqDict.keys())

By default sorted will sort the list of tuple by 1st element in tuple i.e. on 0th index. So list of tuples (key / value pairs) is sorted by keys. Now we can iterate over this sort list of tuple i.e. all sorted keys value pairs from dictionary i.e.
'''
 Iterate over a  list of tuple i.e. key / value pairs, sorted by default 0th index i.e. key
 and print the key value pairs in sorted order of keys
'''
for elem in sorted(wordsFreqDict.items()) :
    print(elem[0] , " ::" , elem[1] )

It will print the dictionary in a sorted order of keys i.e.
at  ::  23
hello  ::  56
test  ::  43
this  ::  43

It’s more efficient than previous method in terms of complexity, because after sorting the iterable sequence we don’t need to search for value for key like in case of dict.keys().

We can achieve the same using List Comprehension i.e.

# Print the sorted key value pairs of dictionary using list comprehension
[ print(key , " :: " , value) for (key, value) in sorted(wordsFreqDict.items()) ]

Sorting dictionary contents in reverse order of keys

Both the previous solutions sorted the dictionary by key but in ascending order. What if we want to sort the contents by descending order of keys. We can so this by simply passing an attribute in sorted() function i.e. reverse=True i.e.

sorted(iterable_sequence, reverse=True)

Let’s use this to sort the list of tuples by keys (0th index element) and in reverse order i.e. descending order,
'''
Iterate over the list of tuples sorted by 0th index i.e. value in reverse order 
'''
for elem in sorted(wordsFreqDict.items(), reverse=True) :
    print(elem[0] , " ::" , elem[1] )

It will print the dictionary in a sorted order of keys in reverse i.e.
this  :: 43
test  :: 43
hello  :: 56
at  :: 23

Sort dictionary contents by key using custom key functions

We can also sort the contents of dictionary by custom logic. Like in case our dictionary we want to sort by the length of key strings.

sorted(iterable_sequence, key Function)

sorted() function accepts a key function as an argument and calls it on each element prior to make comparison with other elements.
So, to sort the dictionary keys by length of string, we will pass a lambda function as key function that will return the size of string i.e.
listofTuples = sorted(wordsFreqDict.items() ,  key=lambda x: len (x[0] ) )

for elem in listofTuples :
    print(elem[0] , " ::" , elem[1] )    

It will create a list of tuples, sorted by key size i.e.
at  :: 23
this  :: 43
test  :: 43
hello  :: 56

Sort dictionary contents by Value

To sort dictionary elements by value we will use the same sorted() function and pass a key function that will return the 1th index element of tuple i.e. the value field from the key/value pair,

# Create a list of tuples sorted by index 1 i.e. value field     
listofTuples = sorted(wordsFreqDict.items() ,  key=lambda x: x[1])

# Iterate over the sorted sequence
for elem in listofTuples :
    print(elem[0] , " ::" , elem[1] )

As this key function will be called on each element before making comparison while sorting, so the list of tuples will be sorted by value i.e.
at  :: 23
this  :: 43
test  :: 43
hello  :: 56

We can do the same using List comprehension too,
# Use List comprehension to print the contents of dictionary , sorted by value
[ print(key , " :: " , value) for (key, value) in sorted(wordsFreqDict.items() ,  key=lambda x: x[1]  ) ]

Sorting dictionary by value in reverse Order

# Create a list of tuples sorted by index 1 i.e. value field     
listofTuples = sorted(wordsFreqDict.items() , reverse=True, key=lambda x: x[1])

# Iterate over the sorted sequence
for elem in listofTuples :
    print(elem[0] , " ::" , elem[1] )    

Output:
hello  :: 56
test  :: 43
this  :: 43
at  :: 23

Dictionary tutorials and examples in Python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

def main():
    
    # Dictionary of strings and ints
    wordsFreqDict = {
        "hello": 56,
        "at" : 23 ,
        "test" : 43,
        "this" : 43
        }
    
    '''
    sort dictionary elements by key
    '''
    print("**** Sort Dictionary by Key *******")
    
    '''
     Iterate over a sorted list of keys and select value from dictionary for each key
     and print the key value pairs in sorted order of keys
    '''
    for key in sorted(wordsFreqDict.keys()) :
        print(key , " :: " , wordsFreqDict[key])
        
    print("***************")
   
    '''
     Iterate over a  list of tuple i.e. key / value pairs, sorted by default 0th index i.e. key
     and print the key value pairs in sorted order of keys
    '''
    for elem in sorted(wordsFreqDict.items()) :
        print(elem[0] , " ::" , elem[1] )
        
    print("***************")
    
    # Print the sorted key value pairs of dictionary using list comprehension
    [ print(key , " :: " , value) for (key, value) in sorted(wordsFreqDict.items()) ]    

    print("***************")
    
    print("Sort dictionary contents by value in reverse Order")

    '''
    Iterate over the list of tuples sorted by 0th index i.e. value in reverse order 
    '''
    for elem in sorted(wordsFreqDict.items(), reverse=True) :
        print(elem[0] , " ::" , elem[1] )
        
    print("***************")
        
    print("Sort by Key using Custom Comparator : Sort by length of key string")    
    listofTuples = sorted(wordsFreqDict.items() ,  key=lambda x: len (x[0] ) )
    
    for elem in listofTuples :
        print(elem[0] , " ::" , elem[1] )    


    '''
    Sort dictionary elements by value
    '''

    print("**** SORT BY VALUE *******")
    
    # Create a list of tuples sorted by index 1 i.e. value field     
    listofTuples = sorted(wordsFreqDict.items() ,  key=lambda x: x[1])
    
    # Iterate over the sorted sequence
    for elem in listofTuples :
        print(elem[0] , " ::" , elem[1] )    

    print("*************************")
    
    # Use List comprehension to print the contents of dictionary , sorted by value
    [ print(key , " :: " , value) for (key, value) in sorted(wordsFreqDict.items() ,  key=lambda x: x[1]  ) ]

    print("**** SORT BY VALUE In Reverse Order *******")
    
    # Create a list of tuples sorted by index 1 i.e. value field     
    listofTuples = sorted(wordsFreqDict.items() , reverse=True, key=lambda x: x[1])
    
    # Iterate over the sorted sequence
    for elem in listofTuples :
        print(elem[0] , " ::" , elem[1] )    
    
if __name__ == '__main__':
    main()

Output:
**** Sort Dictionary by Key *******
at  ::  23
hello  ::  56
test  ::  43
this  ::  43
***************
at  :: 23
hello  :: 56
test  :: 43
this  :: 43
***************
at  ::  23
hello  ::  56
test  ::  43
this  ::  43
***************
Sort dictionary contents by value in reverse Order
this  :: 43
test  :: 43
hello  :: 56
at  :: 23
***************
Sort by Key using Custom Comparator : Sort by length of key string
at  :: 23
test  :: 43
this  :: 43
hello  :: 56
**** SORT BY VALUE *******
at  :: 23
test  :: 43
this  :: 43
hello  :: 56
*************************
at  ::  23
test  ::  43
this  ::  43
hello  ::  56
**** SORT BY VALUE In Reverse Order *******
hello  :: 56
test  :: 43
this  :: 43
at  :: 23

 

Subscribe with us to join a list of 2000+ Programmers for weekly newsletter.