Using Python Dictionaries

30 minutes
  • 4 Learning Objectives

About this Hands-on Lab

Dictionaries are one of the fundamental data types that we use in Python to solve real problems. These are handy when we don’t need a sequential list of items, and it is more useful to have unique identifiers for looking up values. In this hands-on lab, we’ll be working through some exercises demonstrating that we understand how to add, remove, modify, and read items from dictionaries in Python.

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

* Working with dictionary literals. Watch the “Dictionaries” video from the Certified Entry-Level Python Programmer Certification course.
* Using Dictionary functions and methods. Watch the “Dictionary Methods” video from the Certified Entry-Level Python Programmer Certification course.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create the emails Dictionary and Add Initial Items

Our first few tasks require us to create the emails variable that we’re going to work with throughout the lab and then add some information to it. Here’s how we complete the first task: (partial)

# 1) Set the emails variable to be an empty dictionary
emails = {}

assert emails == {}, f"Expected `emails` to be {{}} but got: {repr(users)}"

Now if we run the file (python3.7, we should see the error for the second task:

$ python3.7
Traceback (most recent call last):
  File "", line 12, in <module>
    }, f"Expected `emails` to be {{'ashley': '', 'craig': '', 'elizabeth': ''}} but got: {repr(emails)}"
AssertionError: Expected `emails` to be {'ashley': '', 'craig': '', 'elizabeth': ''} but got: {}

This error shows us that we need to add values to the dictionary before we can continue. The task also specifies that we shouldn’t just reassign the emails variable. Here’s an example solution to this: (partial)

# 2) Add 'ashley', 'craig', and 'elizabeth' to the emails dictionary without reassigning the variable.

emails['ashley'] = ''
emails['craig'] = ''
emails['elizabeth'] = ''

assert emails == {
    'ashley': '',
    'craig': '',
    'elizabeth': ''
}, f"Expected `emails` to be {{'ashley': '', 'craig': '', 'elizabeth': ''}} but got: {repr(emails)}"
Remove craig and Add dalton

For tasks 3 and 4, we need to remove the craig key/value pair and add one called dalton. Here’s an example solution for getting rid of craig: (partial)

# 3) Remove 'craig' from the emails dictionary without reassigning the variable.
del emails["craig"]

assert emails == {
    "ashley": "",
    "elizabeth": "",
}, f"Expected `emails` to be {{'ashley': '', 'elizabeth': ''}} but got: {repr(emails)}"

When we run the script again, we’ll get an error about it expecting a dalton. To fix that, we need to add it in. Here’s how:

# 4) Add 'dalton' to the emails dictionary without reassigning the variable.

emails["dalton"] = ""

assert emails == {
    "ashley": "",
    "elizabeth": "",
    "dalton": "",
}, f"Expected `emails` to be {{'ashley': '', 'elizabeth': '', 'dalton': ''}} but got: {repr(emails)}"

The del statement will allow us to remove an item with the specified key to complete task three. For task four, we’ve just added add another key/value pair.

Return a List of Keys and a List of Values from the emails Dictionary

For tasks five and six we’ll be extracting information from the emails dictionary to populate new lists for users and email_list. The users list will contain all of the keys from emails and the email_list will include all of the values. (partial)

# 5) Return a list of keys from the emails dictionary as `users`
users = list(emails.keys())

assert users == [
], f"Expected `users` to be ['ashley', 'elizabeth', 'dalton'] but got: {repr(users)}"

# 6) Return a list of values from the emails dictionary as `email_list`
email_list = list(emails.values())

assert email_list == [
], f"Expected `email_list` to be ['', '', ''] but got: {repr(email_list)}"
Return a List of Tuples Called pairs Representing the Key/Value Pairs in emails

For the final task, we’ll extract a new list called pairs from emails that will include a 2-tuple for each key/value pair in the emails dictionary. (partial)

# 7) Return a list of tuples called `pairs` representing the key/value pairs in `emails`.
pairs = list(emails.items())

assert pairs == [
    ("ashley", ""),
    ("elizabeth", ""),
    ("dalton", ""),
], f"Expected `pairs` to be [('ashley', ''), ('elizabeth', ''), ('dalton', '')] but got: {repr(pairs)}"

Additional Resources

From within the file, we'll be modifying the users list so that the assertions throughout the file all succeed eventually. As we're working through the tasks we can run the file. Whenever Python gets to a line that starts with assert, it will raise an error and stop executing if we haven't met the criteria. The first error will look like this:

$ python3.7
Traceback (most recent call last):
  File "", line 3, in <module>
    assert users == [], f"Expected `users` to be [] but got: {repr(users)}"
NameError: name 'users' is not defined

This process will show us the line where the issue was encountered, and show us the differences between our expected and actual values.

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.

Once you are in the server, open up (with either VS Code or a command-line text editor) and you can continue.

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?