How to sort a dictionary in python?

A dictionary is a built-in data type in python that stores the data as key-value pair. A dictionary is ordered, mutable, and doesn't allow redundant data. Dictionary is represented with a pair of curly brackets {}. A dictionary can be sorted by keys or by values.

For example let us consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. The dictionary color_dict when sorted by keys gives results as {1: 'red', 2: 'orange', 3: 'black'} and when sorted by value results in {3: 'black', 2: 'orange', 1: 'red'}

Sort a dictionary by keys

Sort a dictionary by keys using items() and sorted() method

The items() method returns view objects that display key-value pairs of the dictionary as tuples in the list. The items() method doesn't take any argument and doesn't return anything.

The sorted() function is a built-in function in python that returns a sorted sequence. The syntax for the sorted() function is as follows.

#syntax:
sorted(seq, key=..., reverse=...)
  • The parameter reverse takes a boolean value. If the reverse is set to True it sorts the list in descending order.
  • The parameter key takes a function as a value for user-defined comparison.

Let us consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. The sorted(color_dict.items()) sorts the dictionary by keys in ascending order and returns the list of tuples [(1, 'red'), (2, 'orange'), (3, 'black')] as output that is stored in a variable view_object.

The dict() constructor converts the list of tuples view_object to a dictionary and gives the final output as {1: 'red', 2: 'orange', 3: 'black'}

color_dict = {2: 'orange', 3: 'black', 1: 'red'}
print("color_dict : ", color_dict)
view_object = sorted(color_dict.items())
print("view_object of sorted dictionary : ", view_object)
print("Sorted Dictionary by keys : ", end= " ")
print(dict(view_object))

The above code gives output as

color_dict :  {2: 'orange', 3: 'black', 1: 'red'}
view_object of sorted dictionary :  [(1, 'red'), (2, 'orange'), (3, 'black')]
Sorted Dictionary by keys :  {1: 'red', 2: 'orange', 3: 'black'}
Sort a dictionary by keys using for loop, keys() and sorted() method

The keys() method returns an iterable view of all the keys in the dictionary. For example, let us consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. color_dict.keys() returns the view object as [2, 3, 1].

A for loop iterates over the sorted list of keys and adds the key-value pair to the sorted_dict in ascending order.

color_dict = {2: 'orange', 3: 'black', 1: 'red'}
print("color_dict : ", color_dict)
sorted_dict = {}
print("color_dict.keys() : ", color_dict.keys())
for key in sorted(color_dict.keys()):
    sorted_dict[key] = color_dict[key]
print("sorted_dict : ", sorted_dict)

The above code returns the output as

color_dict :  {2: 'orange', 3: 'black', 1: 'red'}
color_dict.keys() :  dict_keys([2, 3, 1])
sorted_dict :  {1: 'red', 2: 'orange', 3: 'black'}

In Python 3.6+ dictionaries are ordered. If we want the insertion order to be guaranteed in Python 3.6 and earlier version we can use OrderedDict. OrderedDict() function can be imported from the collections module. The OrderedDict() preserves the sequence of insertion.

Sort a dictionary by values

Sort a dictionary by values using items() and sorted() method

Let us consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. The items() method display key-value pairs of the dictionary as tuples in the list. color_dict.items() returns the view object dict_items([(2, 'orange'), (3, 'black'), (1, 'red')]) as output.

To sort the dictionary by the value we use the sorted() function. The sorted() method takes two parameters, sequence and a key function in the following example. The key function is called on each element before values are compared for sorting.

color_dict.items() is passed to the sequence parameter and the value field from the key-value pair is passed to the key function.

sorted(color_dict.items(), key = lambda x: x[1] ) returns the list of tuples [(3, 'black'), (2, 'orange'), (1, 'red')] sorted by value. The dict() constructor converts the list of tuples in key-value format.

color_dict = {2: 'orange', 3: 'black', 1: 'red'}
print("color_dict : ", color_dict)
view_object = (color_dict.items())
print("view_object : ", view_object)
sorted_dict = dict(sorted(color_dict.items(), key = lambda x: x[1] ))
print("Sorted Dictionary by values : ", sorted_dict)

The above code returns the output as

color_dict :  {2: 'orange', 3: 'black', 1: 'red'}
view_object :  dict_items([(2, 'orange'), (3, 'black'), (1, 'red')])
Sorted Dictionary by values :  {3: 'black', 2: 'orange', 1: 'red'}

Sort a dictionary by values using for loop method

Consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. sorted(color_dict.values()) sorts values in the dictionary and returns ['black', 'orange', 'red'] as output to sorted_val. A sorted_dict is initialized to an empty dictionary.

A for loop iterates over the sorted_val. The nested for loop finds the keys for each value. If the key for a particular value is found, the key-value pair is added to the sorted_dict. The sorted_dict holds a dictionary sorted by values.

color_dict = {2: 'orange', 3: 'black', 1: 'red'}
print("color_dict : ", color_dict)
sorted_val = sorted(color_dict.values())
print("sorted_val : ", sorted_val)
sorted_dict = {}
for val in sorted_val:
    for key in color_dict.keys():
        if (color_dict[key] == val):
            sorted_dict[key] = val
print("sorted_dict : ", sorted_dict)

Output

color_dict :  {2: 'orange', 3: 'black', 1: 'red'}
sorted_val :  ['black', 'orange', 'red']
sorted_dict :  {3: 'black', 2: 'orange', 1: 'red'}

Sort a dictionary by values using itemgetter() and sorted() method

itemgetter() is a inbuilt function in python in operator module. itemgetter() is similar to lambda function, but is more concise and faster in context of time. Consider a list list_1 = [1, 2, 3, 4, 5]. operator .itemgetter(2) returns a value 3. The syntax for itemgetter() is as follows.

#syntax:
operator.itemgetter(attribute)

itemgetter() can be used instead of lambda function to sort a dictionary by value. Let us consider a dictionary color_dict = {2: 'orange', 3: 'black', 1: 'red'}. sorted(color_dict.items(), key = operator.itemgetter(1 )) returns the list of tuples [(3, 'black'), (2, 'orange'), (1, 'red')] sorted by value.

The dict() constructor converts the list of tuples in key-value format.

import operator
color_dict = {2: 'orange', 3: 'black', 1: 'red'}
print("color_dict : ", color_dict)
sorted_dict = dict(sorted(color_dict.items(), key=operator.itemgetter(1)))
print("sorted_dict = ", sorted_dict)  

The above code sorts the dictionary by value and returns the output as

color_dict :  {2: 'orange', 3: 'black', 1: 'red'}
sorted_dict =  {3: 'black', 2: 'orange', 1: 'red'}
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions