Built with Tutify.io

    AIStudyLabs

    Sort List of Dictionaries by Value in Python?

    Sort List of Dictionaries by Value in Python?

    We can sort a list of dictionaries by value using sorted() or sort() function in Python. Sorting is always a useful utility in everyday programming. Using sorted() function we can sort a list of dictionaries by value in ascending order or descending order. This function sorts iterable objects like lists, tuples, sets, and dictionaries.

    In this article, I will explain how to sort a list of dictionaries by value in ascending/descending order using Pyhton sorted() function and this function is also used to sort dictionary by value and sort dictionary by Key in Python.

    <a id="h-1-quick-examples-of-sort-a-list-of-dictionaries-by-value"></a>

    1. Quick Examples of Sort a List of Dictionaries by Value

    If you are in a hurry, below are some quick examples of how to sort a list of dictionaries by value.

    
    # Below are some quick examples.
    
    # Example 1: Sort list of dictionaries using sorted() & lambda
    print(sorted(dict_list, key=lambda x: x['fruit_name']))
    
    # Example 2: Sort list of dictionaries in descending order
    # Using sorted()
    print(sorted(dict_list, key=lambda x: x['fruit_name'], reverse = True))
    
    # Example 3: Sort list of dictionaries when key doesn't exist
    print(sorted(dict_list, key=lambda x: x['calories']))
    
    # Example 4: Sort list of dictionaries using sorted() & get()
    print(sorted(dict_list, key=lambda x: x.get('calories')))
    
    # Example 5: Sort list of dictionaries using sorted() & get()
    # When key doesn't exist
    print(sorted(dict_list, key=lambda x: x.get('calories', 95)))
    
    # Example 6: Set operator.itemgetter() as key and sort
    # List of dictionaries using sorted()
    import operator
    print(sorted(dict_list, key=operator.itemgetter('fruit_name')))
    
    # Example 7: Sort list of dictionaries without key existence 
    # Using operator module
    print(sorted(dict_list, key=operator.itemgetter('calories')))
    
    # Example 8: Sort a list of dictionaries having the same value for multiple keys
    print(sorted(dict_list, key=operator.itemgetter('calories')))
    

    <a id="What-is-Dictionary"></a>

    2. What is Python Dictionary

    A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

    Let's create a list of dictionaries,

    
    # Create a list of dictionaries
    dict_list = [{'fruit_name':'pomegranate', 'no.of alphabets':11, 'calories':11},
                 {'fruit_name':'kiwi', 'no.of alphabets':4, 'calories':42},
                 {'fruit_name':'Apple', 'no.of alphabets':5}, 
                 {'fruit_name':'strawberry', 'no.of alphabets': 10, 'calories':17}]
    print(dict_list)
    

    Yields below output.

    <a id="h-3-sort-list-of-dictionaries-using-sorted-lambda-functions"></a>

    3. Sort List of Dictionaries using sorted() & Lambda Functions

    Python sorted() function can be used to sort the list of dictionaries in an ascending/descending order. When we sort the list of dictionaries using the sorted() or sort() function without specifying key parameter, by default TypeError raises.

    To sort list of dictionaries by value using sorted() function we need to specify the key Parameter.

    Let's sort the list of dictionaries using the sorted() function and lambda function. In this example, I will specify the key parameter with fruit_name. This syntax will sort the given list of dictionaries by value according to 'fruit_name'.

    
    # Sort list of dictionaries using sorted() & lambda
    # According to 'fruit_name'
    print(sorted(dict_list, key=lambda x: x['fruit_name']))
    

    Yields below output.

    Let's see another example of the list of dictionaries using sorted() function.

    
    # Sort list of dictionaries using sorted() & lambda
    # According to 'no.of alphabets' 
    print(sorted(dict_list, key=lambda x: x['no.of alphabets']))
    
    # Output:
    # [{'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}, {'fruit_name': 'Apple', 'no.of alphabets': 5}, 
    #  {'fruit_name': 'strawberry', 'no.of alphabets': 10, 'calories': 17}, {'fruit_name': 'pomegranate', 'no.of 
    #  alphabets': 11, 'calories': 11}]
    

    <a id="h-4-sort-list-of-dictionaries-in-descending-order-in-python"></a>

    4. Sort List of Dictionaries in Descending Order in Python

    Let's use the sorted() function to sort the list of dictionaries in descending order. For that, we need to set the reverse param of the sorted() function as True and pass it into this function. It will sort the list of dictionaries by value with a specified key param in descending order.

    
    # Sort list of dictionaries in descending order
    # Using sorted()
    print(sorted(dict_list, key=lambda x: x['fruit_name'], reverse = True))
    
    # Output:
    # [{'fruit_name': 'strawberry', 'no.of alphabets': 10, 'calories': 17}, {'fruit_name': 'pomegranate', 'no.of 
    #  alphabets': 11, 'calories': 11}, {'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}, {'fruit_name': # 'Apple', 'no.of alphabets': 5}]
    

    So far, we have learned how to sort the list of dictionaries using the sorted() method. Similarly, we can also sort the list of dictionaries using the sort() function by specifying the key and reverse param. Only the difference between the sort() and sorted() function is sort() method sorts existing objects and sorted() method generates a new sorted object.

    <a id="when-the-specified-key-does-not-exist"></a>

    5. Sort List of Python Dictionaries When Specified Key does not Exist

    When we use the sorted() method to sort the list of dictionaries by value with a specified key, which does not exist in the dictionary. It will raise the KeyError.

    
    # Sort list of dictionaries when key doesn't exist
    print(sorted(dict_list, key=lambda x: x['calories']))
    
    # Output:
    # KeyError
    

    Alternatively, we can use the Python dictionary get() method, which returns the default value None for every non-existing key. None, which is not comparable to a number or a string, so an error raises.

    
    # Sort list of dictionaries using sorted() & get()
    print(sorted(dict_list, key=lambda x: x.get('calories')))
    
    # Output:
    # TypeError: '<' not supported between instances of 'NoneType' and 'int'
    

    To overcome TypeError we can specify the value whose key doesn't exist in the dictionary and pass it as a second param of get() method. It will sort the list of dictionaries when the key doesn't exist in the dictionary.

    
    # Sort list of dictionaries using sorted() & get()
    # When key doesn't exist
    print(sorted(dict_list, key=lambda x: x.get('calories', 95)))
    
    # Output:
    # [{'fruit_name': 'pomegranate', 'no.of alphabets': 11, 'calories': 11}, {'fruit_name': 'strawberry', 'no.of 
    # alphabets': 10, 'calories': 17}, {'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}, {'fruit_name': 
    # 'Apple', 'no.of alphabets': 5}]
    

    As we can see from the above, The list has been sorted according to 'calories'.

    <a id="specify-operatoritemgetter-for-the-key-parameter"></a>

    6. Sort using Set operator.itemgetter() as key parameter

    Set operator.itemgetter() as a key parameter of sorted() function to sort the list of dictionaries by value with a specified key. itemgetter() is an operator module of the standard library. It can sort faster than using a lambda expression.

    Sort a list of dictionaries by value according to the 'fruit_name' key.

    
    # Set operator.itemgetter() as key and sort
    # List of dictionaries using sorted()
    import operator
    print(sorted(dict_list, key=operator.itemgetter('fruit_name')))
    
    # Output:
    # [{'fruit_name': 'Apple', 'no.of alphabets': 5}, {'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}, # {'fruit_name': 'pomegranate', 'no.of alphabets': 11, 'calories': 11}, {'fruit_name': 'strawberry', 'no.of 
    # alphabets': 10, 'calories': 17}]
    

    <a id="h-7-sort-descending-order-using-set-operator-itemgetter"></a>

    7. Sort Descending order using Set operator.itemgetter()

    Set reverse param as True and pass it into sorted() method along with itemgetter(), it will sort the list of dictionaries in descending order.

    
    # Sort list of dictionaries in descending order 
    # Using itemgetter()
    import operator
    print(sorted(dict_list, key=operator.itemgetter('fruit_name'), reverse = True)) 
    
    # Output:
    # [{'fruit_name': 'strawberry', 'no.of alphabets': 10, 'calories': 17}, {'fruit_name': 'pomegranate', 'no.of 
    # alphabets': 11, 'calories': 11}, {'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}, {'fruit_name': 
    # 'Apple', 'no.of alphabets': 5}]
    

    When we sort the list of dictionaries by value without key occurrence using the operator module, KeyError will raise.

    
    # Sort list of dictionaries without key existence 
    # Using operator module
    print(sorted(dict_list, key=operator.itemgetter('calories')))
    
    # Output:
    # KeyError
    

    <a id="sort-by-multiple-keys"></a>

    8. Sort List of Python Dictionaries having Same Value for Multiple Keys

    When we sort the list of dictionaries having the same value for multiple keys using sorted() function, it will sort the list of dictionaries and preserve the existing order. Let's take an example,

    
    # Create dictionary
    dict_list = [{'fruit_name':'pomegranate', 'no.of alphabets':11, 'calories':11},
                 {'fruit_name':'kiwi', 'no.of alphabets':4, 'calories':42},
                 {'fruit_name':'Apple', 'no.of alphabets':5, 'calories':17}, 
                 {'fruit_name':'strawberry', 'no.of alphabets': 10, 'calories':17}]
    print(dict_list)
    import operator
    # Sort a list of dictionaries having the same value for multiple keys
    print(sorted(dict_list, key=operator.itemgetter('calories')))
    
    # Output:
    
    # [{'fruit_name': 'pomegranate', 'no.of alphabets': 11, 'calories': 11}, {'fruit_name': 'Apple', 'no.of alphabets': 5, 'calories': 17}, {'fruit_name': 'strawberry', 'no.of alphabets': 10, 'calories': 17}, {'fruit_name': 'kiwi', 'no.of alphabets': 4, 'calories': 42}]
    

    <a id="h-9-conclusion"></a>

    9. Conclusion

    In this article, I have explained how to sort a list of dictionaries by value in ascending/descending order using Pyhton sorted(), sort(), lambda function, and itemgetter() functions with examples.