How to Sort a Dictionary by Value in Python

Posted in /  

How to Sort a Dictionary by Value in Python
vinaykhatri

Vinay Khatri
Last updated on April 24, 2024

    Python has 4 major built-in data structures Python list , Python tuples , Python sets , and Python dictionary , and all these data structures are used to store elements or items. And when we perform the sorted () function on every data structure, we get a list of sorted elements from that data structure.

    For example

    >>> my_list =[5,32,23,22]
    >>> sorted(my_list)
    [5, 22, 23, 32]
    
    >>> my_tuples = (5, 37,98,88)
    >>> sorted(my_tuples)
    [5, 37, 88, 98]
    
    >>> my_sets = {3,45,22,78,91}
    >>> sorted(my_sets)
    [3, 22, 45, 78, 91]

    For every data structure, the Python sorted() function returns a sorted list object, which is fine because, at last, we are getting the sorted values. But this is not the case with Python dictionaries, the sorted() function returns a listed list of sorted dictionary keys, not values.

    >>> my_dict = {2:'two', 3:'three', 1:'one'}
    
    >>> sorted(my_dict)
    [1, 2, 3]

    In the above example, you can see that the sorted() function returns a list of sorted keys, not values. So be careful when you use the sorted() method on a dictionary because, in return, you get sorted keys, not values. But this behavior of sorted() method can be manipulated by passing the key parameter. And with that, we can eventually sort a Python dictionary by its values using the sorted() function.

    Python sorted() Function

    sorted() is a Python function that accepts an iterable object as a parameter, sorts the iterable elements according to the lexicographical order and returns a list containing sorted elements. The iterable object can either be a list, tuple, set, or Dictionary.

    Python sorted() method syntax

    sorted(iterable_object, key, reverse)
    
    

    The sorted() method can accept 3 parameters

    • iterable_object represent the object which you want to sort, and it is a required parameter.
    • key parameter represents on what basis you want to sort the iterable object and this parameter is optional.
    • reverse represents that the return list will be sorted in reverse order, and this parameter is also optional.

    Python sorted() methods Example 1

    my_list = ["z", "a", "m", "k", "b", "C", "c", "l"]
    
    #sorted() method only with iterable object
    print(sorted(my_list))

    Output

    ['C', 'a', 'b', 'c', 'k', 'l', 'm', 'z']
    
    

    ASCII values for A-Z range from 65 to 90, and a-z range from 97 to 122. That’s why A is smaller than a.

    <Note>: The sorted() element only work if the elements present in the iterable object are of the same data type.

    Python sorted() methods Example 2

    my_list = ["z", "a", "m", "k", "b", "C", "c", "l"]
    
    #sorted() method with iterable object and key parameter
    print(sorted(my_list, key =str.lower))

    Output

    ['a', 'b', 'C', 'c', 'k', 'l', 'm', 'z']
    
    

    The key parameter accepts a function or method which describes on what basis the values of the iterable but be sorted. Here, by mentioning the str.lower we specify that performing the str.lower method on every element of the my_list and then sort.

    Python sorted() methods Exxample3

    my_list = ["z", "a", "m", "k", "b", "C", "c", "l"]
    
    #sorted() method with iterable object, key, and reverse parameters
    print(sorted(my_list, key =str.lower, reverse=True))

    Output

    ['z', 'm', 'l', 'k', 'C', 'c', 'b', 'a']

    The reverse parameter accepts the boolean values True and False, and by default, its value is False. By specifying the True value, the sorted() method sort the iterable elements in reverse order.

    Sort a dictionary by its value using the sorted() method

    If we apply the sorted() method on a dictionary, then we receive a list of sorted dictionary keys, not values. However, this behavior of the sorted() method can be manipulated using the key parameter.

    how to the Python dictionary by its values

    When we apply the sorted() method to a dictionary, we also need to specify a function to the key parameter, which returns the value for every item present in the dictionary. The key parameter accepts a function which applied to every item present in the dictionary as a tuple pair of keys and values.

    Sort a Python dictionary values example 1

    def sort_func(item):
            #here item would come like('onion', 70)
            #return the second index, which represent value
            return item[1]
    
    prices ={'onion':70, 'tomato':40, 'cheese': 400, 'garlic':30, 'potato':20, 'sugar':80}
    
    sorted_prices = sorted(prices.items(), key= sort_func, reverse=False)
    
    for i in sorted_prices:
        print(i[0], ":",i[1])

    Output

    potato : 20
    garlic : 30
    tomato : 40
    onion : 70
    sugar : 80
    cheese : 400

    Sort a Python dictionary values example 2

    The same above example can be performed using the Python lambda function

    prices ={'onion':70, 'tomato':40, 'cheese': 400, 'garlic':30, 'potato':20, 'sugar':80}
    sorted_prices = sorted(prices.items(), key= lambda item: item[1], reverse=False)
    for i in sorted_prices:
            print(i[0], ":",i[1])

    Output

    potato : 20
    garlic : 30
    tomato : 40
    onion : 70
    sugar : 80
    cheese : 400
     

    Sort the Python dictionary values in descending order.

    To sort Python dictionary values in descending order, we just need to specify the reverse parameter to True

    Example:

    prices ={'onion':70, 'tomato':40, 'cheese': 400, 'garlic':30, 'potato':20, 'sugar':80}
    sorted_prices = sorted(prices.items(), key= lambda item: item[1], reverse=True)
    for i in sorted_prices:
        print(i[0], ":",i[1])

    Output

    cheese : 400
    sugar : 80
    onion : 70
    tomato : 40
    garlic : 30
    potato : 20

    Sort the Python dictionary without mentioning the key parameter

    You do not need to go around so much and do not even specify the key parameter, to sort Python dictionary values. Python dictionary method provides a values() method that returns a list of all values present in the dictionary. Using the values() method, we can grab all the values, and using the sorted method; we can directly sort the values.

    Example

    prices ={'onion':70, 'tomato':40, 'cheese': 400, 'garlic':30, 'potato':20, 'sugar':80}
    sorted_prices = sorted(prices.values())
    for i in sorted_prices:
        print(i)

    Output

    20
    30
    40
    70
    80
    400

    Conclusion

    Here in this Python tutorial, you learned how can you sort Python dictionary values. Here you also learned all about the Python sorted() method and all of its acceptable parameters. In a sorted() method, only an iterable object is a required parameter and key and reverse are optional. And if you want to sort a python dictionary by its value, then you need to specify the key parameter returning the second value for every item. You can also use the values() method and sort the Python dictionary values, but in that case, you would not have direct access to the values corresponding key, so it would be better to use the key approach instead of values().

    People are also reading:

    Leave a Comment on this Post

    0 Comments