First, you have to put names in quotes, otherwise it's illegal in python.
Then maybe this will make it easier to understand:
>>> employees = [
... {'Name': 'Allan', 'Age': 25, 'Salary': 10000},
... {'Name': 'Sharon', 'Age': 30, 'Salary': 8000},
... {'Name': 'John', 'Age': 18, 'Salary': 1000}
... ]
>>>
>>> sorted( employees, key = lambda x : x['Name'] )
[
{'Salary': 10000, 'Age': 25, 'Name': 'Allan'},
{'Salary': 1000, 'Age': 18, 'Name': 'John'},
{'Salary': 8000, 'Age': 30, 'Name': 'Sharon'}
]
Make note, I don't use any external function, just the lambda, which has no name, just a single parameter (x in our case), that's one of the items on your list, and it returns the key according to which the list will be sorted. You may try to return x['Salary'] or x['Age'] and see the result. The name get_name is quite accidental and has absolutely no influence. Things are actually much easier with lambdas.
First, you have to put names in quotes, otherwise it's illegal in python.
Then maybe this will make it easier to understand:
>>> employees = [
... {'Name': 'Allan', 'Age': 25, 'Salary': 10000},
... {'Name': 'Sharon', 'Age': 30, 'Salary': 8000},
... {'Name': 'John', 'Age': 18, 'Salary': 1000}
... ]
>>>
>>> sorted( employees, key = lambda x : x['Name'] )
[
{'Salary': 10000, 'Age': 25, 'Name': 'Allan'},
{'Salary': 1000, 'Age': 18, 'Name': 'John'},
{'Salary': 8000, 'Age': 30, 'Name': 'Sharon'}
]
Make note, I don't use any external function, just the lambda, which has no name, just a single parameter (x in our case), that's one of the items on your list, and it returns the key according to which the list will be sorted. You may try to return x['Salary'] or x['Age'] and see the result. The name get_name is quite accidental and has absolutely no influence. Things are actually much easier with lambdas.
sort defines what it will do with key. sort expects key to be a callable (i.e. function), which it will call and pass one element of the list to it. sort will call key for each element in the list. The function that you pass (get_name) must match this definition, not the other way around.
employee in def get_name(employee) is an arbitrary parameter name. You define the function, you can name your parameters anything you want.
Videos
Hi there, I was learning about the lambda/anonymous functions. And I came across this example which sorts a list:
lst = ["Mouse Keyboard", "Router Hub", "CPU UPS"]
lst.sort(key = lambda each: each.split(" ")[-1].lower())
print(lst)
# Which returns output:-
# ['Router Hub', 'Mouse Keyboard', 'CPU UPS']
I tried to google this but was not successful enough. If someone kindly enlightens me on what the key in the sort() function is for. With the google search, I concluded that it takes a function as input. So, the input here will be the 2nd word of each item in the list. But I'm unable to figure out how the sorting function is performed.