DEV Community


Discussion on: Charm the Python: Lambdas

vickilanger profile image
Vicki (she/her) Author

I think this is what I was referring to, but I’m not super sure. All the examples I saw were using functions like map(), filter(), and sort()

I’ve never seen key used before. Help me out, what is x doing in this?

If I’m reading this correctly, it’s just sorting these key-value pairs by age, right?

moopet profile image
Ben Sinclair

yes, array.sort and sorted take a named parameter in Python 3 (I had to learn this a couple of days ago!) which is run as a callback, once per key, immediately before sorting the elements. So that example calls x: x["age"] on every element first.
It's the equivalent of this:

sort([x["age"] for x in my_list])

and this:

def by_age(x):
    return x["age"]

sort(my_list, key = by_age)