Lambdas
Let's sort some objects
presenters = [
{'name': 'Susan', 'age': 50},
{'name': 'Christopher', 'age': 47}
]
presenters.sort() --------------------------------------------------------------------------- TypeError
Traceback (most recent call last) <ipython-input-3-a95aedfc00c9>
print(presenters) in <module>
4]
5
----> 6 presenters.sort()
TypeError: '<' not supported between instances of 'dict' and 'dict'
Notes about sort
sort can automatically handle primitive types and strings
If we need to do anything complex we need to tell sort how to
sort
In this case we just need to specify whether to sort by age or
name
the key parameter allows you to pass in a function to call for
each list element before it compares items for sorting
Let's sort by name
def sorter(item):
return item['name']
presenters = [
{'name': 'Susan', 'age': 50},
{'name': 'Christopher', 'age': 47}
]
presenters.sort(key=sorter)
print(presenters)
[{'name': 'Christopher'}, {'name': 'Susan'}]
Let's do the same thing inline
presenters = [
{'name': 'Susan', 'age': 50},
{'name': 'Christopher', 'age': 47}
]
presenters.sort(key=lambda item: item['name'])
print(presenters)
[{'name': 'Christopher'}, {'name': 'Susan'}]
How lambdas work
Paramet
er
def sorter(item):
return item['name']
Return value
Paramet
er
lambda item: item['name']
Return value
Let's sort by name length (short to
long)
presenters = [
{'name': 'Susan', 'age': 50},
{'name': 'Christopher', 'age': 47}
]
presenters.sort(key=lambda item:
len(item['name']))
print(presenters)
[{'name': 'Susan'}, {'name': 'Christopher'}]
© 2016 Microsoft Corporation. All rights reserved. The text in this document is available under the Creative Commons Attribution 3.0 License, additional terms may apply. All other
content contained in this document (including, without limitation, trademarks, logos, images, etc.) are not included within the Creative Commons license grant. This document does
not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes.
This document is provided "as-is." Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear
the risk of using it. Some examples are for illustration only and are fictitious. No real association is intended or inferred. Microsoft makes no warranties, express or implied, with
respect to the information provided here.