[Python] trying to understand sort(key = ...) function

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following list:

    employees = [
    {'Name': Allan, 'Age': 25, 'Salary': 10000},
    {'Name': Sharon, 'Age': 30, 'Salary': 8000},
    {'Name': John, 'Age': 18, 'Salary': 1000}
    ]


    And I want to sort this list by taking the 'Name' key as reference. For this purpose, the source I've ben studying has given the following function:

    def get_name(employee):
    return employee.get('Name')

    employees.sort(key = get_name)


    If I now run print(employees), it sorts out the dictionary as I want to.

    My question here is, how does the interpreter understands, what the parameter 'employee' is? It is nowhere defined and it has actually nothing to do with the list "employees". It is a bit confusing for me.

    I would appreciate, if anybody explains it. Thanks!

    Continue reading...

Compartilhe esta Página