Processing Collections in Python Using Lambdas

30 minutes
  • 3 Learning Objectives

About this Hands-on Lab

Being able to perform actions on a collection is incredibly useful in any type of programming, and it is pretty common to need to perform a single action on each item. We could do this by using a loop, but there are built-in collection functions that can take a collection and a function or lambda to run each item through. In this hands-on lab, we utilize higher-order functions to process some existing lists by using lambdas.

To feel comfortable completing this lab you’ll want to know how to do the following:

– Define and use lambdas. Watch “Defining and Using Lambdas” from the Certified Associate in Python Programming Certification course.
– Use higher-order functions and collection functions. Watch “Using Collection Functions” from the Certified Associate in Python Programming Certification course.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create the `sorted_by_name` List by Sorting the `people` List of Dictionaries

To sort our list of dictionaries we’re going to use the sorted function. Not all of the values for the name key in our dictionaries start with a capital letter, and because of that, we’re going to want to convert all of the strings to lowercase before making the comparison. Thankfully, we can do this by passing a lambda for the key parameter. Here’s how we can complete the first task:

collection_processing.py

# 1) Sort the `people` list of dictionaries alphabetically based on the
# 'name' key from each dictionary using the `sorted` function and store
# the new list as `sorted_by_name`

people = [
    {"name": "Kevin Bacon", "age": 61},
    {"name": "Fred Ward", "age": 77},
    {"name": "finn Carter", "age": 59},
    {"name": "Ariana Richards", "age": 40},
    {"name": "Victor Wong", "age": 74},
]

sorted_by_name = sorted(people, key=lambda d: d['name'].lower())

assert sorted_by_name == [
    {"name": "Ariana Richards", "age": 40},
    {"name": "finn Carter", "age": 59},
    {"name": "Fred Ward", "age": 77},
    {"name": "Kevin Bacon", "age": 61},
    {"name": "Victor Wong", "age": 74},
], f"Expected sorted_by_name to equal '{sorted_by_name}' to equal '{[{'name': 'Ariana Richards', 'age': 40}, {'name': 'finn Carter', 'age': 59}, {'name': 'Fred Ward', 'age': 77}, {'name': 'Kevin Bacon', 'age': 61}, {'name': 'Victor Wong', 'age': 74}]}''"

Running the script, we should see the following error. This indicates that we’ve successfully met the requirements for the first task.

$ python3.7 collection_processing.py
Traceback (most recent call last):
  File "collection_processing.py", line 36, in <module>
    ], f"Expected name_declarations to equal '{name_declarations}' to equal '{['Ariana Richards is 40 years old', 'finn Carter is 59 years old', 'Fred Ward is 77 y
ears old', 'Kevin Bacon is 61 years old', 'Victor Wong is 74 years old']}'"
AssertionError: Expected name_declarations to equal 'None' to equal '['Ariana Richards is 40 years old', 'finn Carter is 59 years old', 'Fred Ward is 77 years old', 'Kevin Bacon is 61 years old', 'Victor Wong is 74 years old']'
Create the `name_declarations` List by Mapping over `sorted_by_name`

Our second task is to create a list where each string uses the name and age parameters to build strings of <NAME> is <AGE> years old. Let’s create the name_declarations variable:

collection_processing.py

# 2) Use the `map` function to iterate over `sorted_by_name` to generate a
# new list called `name_declarations` where each value is a string with
# `<NAME> is <AGE> years old.` where the `<NAME>` and `<AGE>` values are from
# the dictionaries.

name_declarations = list(
    map(lambda d: f"{d['name']} is {d['age']} years old", sorted_by_name)
)

assert name_declarations == [
    "Ariana Richards is 40 years old",
    "finn Carter is 59 years old",
    "Fred Ward is 77 years old",
    "Kevin Bacon is 61 years old",
    "Victor Wong is 74 years old",
], f"Expected name_declarations to equal '{name_declarations}' to equal '{['Ariana Richards is 40 years old', 'finn Carter is 59 years old', 'Fred Ward is 77 years old', 'Kevin Bacon is 61 years old', 'Victor Wong is 74 years old']}'"

Note that we need to convert the result of map to be a list, otherwise our name_declarations variable will be a map object.

Running our script again, this is what we should see:

python3.7 collection_processing.py
Traceback (most recent call last):
  File "collection_processing.py", line 50, in <module>
    ], f"Expected under_seventy to equal '{under_seventy}' to equal '{[{'name': 'Ariana Richards', 'age': 40}, {'name': 'finn Carter', 'age': 59}, {'name': 'Kevin Bacon', 'age': 61}]}'"
AssertionError: Expected under_seventy to equal 'None' to equal '[{'name': 'Ariana Richards', 'age': 40}, {'name': 'finn Carter', 'age': 59}, {'name': 'Kevin Bacon', 'age': 61}]'
Create the `under_seventy` List by Filtering and Sorting on the `sorted_by_name` List

Our last task is to filter the values in sorted_by_name so our output list only includes dictionaries that have an age value less than 70. To achieve this, we’re going to combine filter and sorted to create our final list.

collection_processing.py

# 3) Combine the `filter` and `sorted` functions to iterate over `sorted_by_name` to generate a
# new list called `under_seventy` that only contains the dictionaries where the
# 'age' key is less than 70, sorting the list by age.

under_seventy = sorted(
    filter(lambda d: d['age'] < 70, sorted_by_name), key=lambda d: d['age']
)

assert under_seventy == [
    {"name": "Ariana Richards", "age": 40},
    {"name": "finn Carter", "age": 59},
    {"name": "Kevin Bacon", "age": 61},
], f"Expected under_seventy to equal '{under_seventy}' to equal '{[{'name': 'Ariana Richards', 'age': 40}, {'name': 'finn Carter', 'age': 59}, {'name': 'Kevin Bacon', 'age': 61}]}'"

Running our script one last time we should see no output because all of the assertions were true.

Additional Resources

The map, filter, sorted, and reversed functions are great examples of higher-order functions that can receive a function (or lambda) as an argument and do things accordingly. In this hands-on lab, we're going to leverage these functions and lambdas to process some pre-created lists within the collection_processing.py script.

To verify that we're getting the proper results, we can run the script and it will throw an error if our expectations aren't met. If we've met all expectations then we won't see any output at all, like this:

$ python3.7 collection_processing.py
$

Logging In

Using the Terminal To Complete the Lab

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the lab, log in with SSH, and use a text editor in the terminal, such as Vim.

Note: When copying and pasting code into Vim from the lab guide, first enter :set paste (and then i to enter insert mode) to avoid adding unnecessary spaces and hashes. To save and quit the file, press Escape followed by :wq. To exit the file without saving, press Escape followed by :q!.

Using VS Code To Complete the Lab

You can also access the lab using VS Code in the browser. If you'd like to go this route, then follow the steps below:

  1. Navigate to the public IP address of the workstation server (provided in your lab credentials) on port 8080, using http (e.g., http://PUBLIC_IP:8080).
  2. If you receive a notification indicating the connection is not secure, click Advanced. Then, proceed to the server.
  3. Use the password provided in your lab credentials.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?