1

We have, for example:

rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]

and

rows_by_fname = sorted(rows, key=lambda r: r['fname'])

this,

key=lambda r: r['fname']

how does it work? as my understanding that r is input for lambda function, right? and that r must be equal to rows, but we never called that lambda function and passed any arguments so what gets assigned to r and how?

  • `sorted` calls the lambda function with each of the elements of `rows` as arguments, and sorts it according to the results of the function, in this case the `fname` – Maarten Fabré May 14 '18 at 12:53
  • 4
    just read the doc [key functions](https://docs.python.org/3/howto/sorting.html#key-functions) – Konstantin May 14 '18 at 12:56
  • yes, that makes sense @MaartenFabré, thanks. – hsetih esilahc May 14 '18 at 13:00
  • 1
    Possible duplicate of [Syntax behind sorted(key=lambda: ...)](https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda), [What is key=lambda](https://stackoverflow.com/questions/13669252/what-is-key-lambda) – Ilja Everilä May 14 '18 at 13:59

1 Answers1

0

The r parameter in your function lambda r: r['fname'] receives each element of the array rows. And then, the lambda function define the keys that will be sorted by the function sorted(). In this case, the keys will be fname.

Is the sorted() that calls the lambda function. The reason to use lambda is because the function will be used only once.

Edit: Read the key docs

reisdev
  • 3,215
  • 2
  • 17
  • 38