Search code examples
pythonpython-3.x

Why hasnt key= been documented?


I'm a beginner so I might be straight up wrong in asking this but I was following a course and I was confused on how to sort a dictionary using a function, with the function returning the key inside that dictionary.

I've had to do some testing to see what conditions I can use the key= for, I realised I could use it on max, but when trying to use it with sort I was stumped, I looked online for how to use key= and all I got was keys(), am I missing some understanding or has this been something not well documented?

What I tried:

def name_alphabetical(student):
    return student["name"]
students = [
    {"name": "Hannah", "grade_average": 83},
    {"name": "Charlie", "grade_average": 91},
    {"name": "Peter", "grade_average": 85},
    {"name": "Rachel", "grade_average": 79},
    {"name": "Lauren", "grade_average": 92}
]

print(students.sort(key(name_alphabetical))

What worked:

def n(student):
    return student["name"]

students = [
    {"name": "Hannah", "grade_average": 83},
    {"name": "Charlie", "grade_average": 91},
    {"name": "Peter", "grade_average": 85},
    {"name": "Rachel", "grade_average": 79},
    {"name": "Lauren", "grade_average": 92}
]

students.sort(key=n)
print(students)

Desired result:

[
    { 'name': 'Charlie', 'grade_average': 91 }, 
    { 'name': 'Hannah', 'grade_average': 83 },
    { 'name': 'Lauren', 'grade_average': 92 },
    { 'name': 'Peter', 'grade_average': 85 }, 
    { 'name': 'Rachel', 'grade_average': 79 }
]

Solution

  • It is documented for sorted():

    sorted(iterable, /, *, key=None, reverse=False)

    key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

    and list.sort():

    sort(*, key=None, reverse=False)

    key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

    You can also use the REPL for a more compact version of the docs:

    >>> help(list.sort)
    
    Help on method_descriptor:
    
    sort(self, /, *, key=None, reverse=False)
    
        Sort the list in ascending order and return None.
    
        The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
        order of two equal elements is maintained).
    
        If a key function is given, apply it once to each list item and sort them,
        ascending or descending, according to their function values.
    
        The reverse flag can be set to sort in descending order.