Sort list of Dictionary Item using Lambda with OOPS

Problem Statement: When you have list where the list items are dictionary and you want your list to be sorted on the basis of specific dictionary Key, you wont be able to directly use the sort method of List, instead you need to use Sorted Method.

Solution:

Lets say you have List like below and you were asked to sort this list on the basis of List item where the list items are dictionary with two keys, and you ask is to sort on the basis of emp_name

my_list = [{'emp_name': 'Varuag', 'emp_performance_score': 25},
           {'emp_name': 'Nitin', 'emp_performance_score': 39},
           {'emp_name': 'Peedarp', 'emp_performance_score': 45},
           {'emp_name': 'Kcillam', 'emp_performance_score': 40},
           {'emp_name': 'Abitoyj', 'emp_performance_score': 31}]

then to do this you can make use of Sorted Method, below is the syntax of Sorted Method

SORTED(itrable_structure, key = function , reverse = True/False)

itterable_structure : Where the itterable object in our case would be list which we want to sort.

Key: key=lambda k: k[’emp_name’], where each dictionary item of list is passed and the lambda function return only the emp_name key value

Reverse : False, as we don’t want to reverse. We are going to use Sorted function like this

@staticmethod
def sort_dict_item_with_single_key_using_lamda_and_sorted(list_of_dict: list) -> list:
    list_of_dict = sorted(list_of_dict, key=lambda k: k['emp_name'])
    return list_of_dict

Lets us now see the whole code:

# Sort list of Dictionary Item using Lamda with Oops

class DictionaryCustomOperation:
    def __init__(self):
        self._cache_dict_list = []

    @staticmethod
    def sort_dict_item_with_single_key_using_lamda_and_sorted(list_of_dict: list) -> list:
        list_of_dict = sorted(list_of_dict, key=lambda k: k['emp_name'])
        return list_of_dict



if __name__ == '__main__':
    my_list = [{'emp_name': 'Varuag', 'emp_performance_score': 25},
               {'emp_name': 'Nitin', 'emp_performance_score': 39},
               {'emp_name': 'Peedarp', 'emp_performance_score': 45},
               {'emp_name': 'Kcillam', 'emp_performance_score': 40},
               {'emp_name': 'Abitoyj', 'emp_performance_score': 31}]

    print(DictionaryCustomOperation.sort_dict_item_with_single_key_using_lamda_and_sorted(my_list))
Output:
C:\PyProjects\myProj2\venv_myproj2\Scripts\python312.exe C:\PyProjects\myProj2\ElfinCode\ListOfDictSort.py 

[{'emp_name': 'Abitoyj', 'emp_performance_score': 31}, {'emp_name': 'Kcillam', 'emp_performance_score': 40}, {'emp_name': 'Nitin', 'emp_performance_score': 39}, {'emp_name': 'Peedarp', 'emp_performance_score': 45}, {'emp_name': 'Varuag', 'emp_performance_score': 25}]

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *