Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – using lambda to create an anonymous function


Why would you want an anonymous function? Let's try sorting a list of dictionaries:

data = [{'Name':'Albert', 'age':32}, 
    {'Name':'Yuen', 'age':16},
    {'Name':'Priya', 'age':45}]

print(sorted(data))
print(sorted(data, key=lambda item : item['age']))

The results should look like this:

What just happened?

We defined a list of dictionaries, each of which contains data about a person. We then used the sorted function to sort the items in the list. The first time we called sorted, it appeared that the list had been sorted alphabetically, by the first letter of each name. This behaviour is unpredictable—if we added a last name to each dictionary, would the first or last name be used as the sorting key? To prevent this kind of problem, we can use the keyword key to specify a function that is called on each item before sorting takes place. In the second function call, we used lambda to define an anonymous function that returns the...