DEV Community

Discussion on: Charm the Python: Lambdas

Collapse
 
moopet profile image
Ben Sinclair

For your example of a "function inside another function", do you mean something like this?

my_list = (
    {
        "name": "Ben",
        "age": "99"
    },
    {
        "name": "Antigone",
        "age": "49"
    },
    {
        "name": "Jonas",
        "age": "10"
    },
    {
        "name": "Samantha",
        "age": "52"
    },
    {
        "name": "Vicki",
        "age": "22"
    }
)

print (sorted(my_list, key = lambda x: x["age"]))
Collapse
 
vickilanger profile image
Vicki Langer

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?

Collapse
 
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)