Python Basics 3#

Description: This lesson describes the basics of lists and dictionaries including:

This is part 3 of 5 in the series Python Basics that will prepare you to do text analysis using the Python programming language.


In Python Basics 1, we learned about three data types: integers, floats, and strings. In this lesson, we will learn about two additional data types: lists and dictionaries. Lists and dictionaries help us store many values inside a single variable. This is helpful for a few reasons.

  • We can store many items in a single list or dictionary, making it easier to keep the data together

  • Lists and dictionaries only require a single assignment statement

  • Lists and dictionaries have additional capabilities that will make organizing our data easier

The fundamental difference between a list and a dictionary is that a list stores items in sequential order (starting from 0) while a dictionary stores items in key/value pairs. When we want to retrieve an item in a list, we use an index number or a set of index numbers called a slice as a reference. When we want to retrieve an item from a dictionary, we supply a key that returns the value (or set of values) associated with that key. Each of these approaches can be beneficial depending on what kind of data we are working with (and what we intend to do with the data).

Lists#

A list can store anywhere from zero to millions of items. The items that can be stored in a list include the data types we have already learned: integers, floats, and strings. A list assignment statement takes the form. my_list = [item1, item2, item3, item4…]

my_list = [item1, item2, item3, item4...]

# A list containing integers
my_favorite_numbers = [7, 21, 100]
print(my_favorite_numbers)
[7, 21, 100]
# A list containing strings
my_inspirations = ['Harriet Tubman', 'Rosa Parks', 'Pauli Murray']
print(my_inspirations)
['Harriet Tubman', 'Rosa Parks', 'Pauli Murray']

Both my_favorite_numbers and my_inspirations have three items, but we could have also initialized them with no items my_favorite_numbers = [] or many more items.

List Index#

Each item has an index number that depends on their order. The first item is 0, the second item is 1, the third item is 2, etc. In the my_inspirations list, 'Pauli Murray' is item 2.

# Retrieving an item in a list
my_inspirations[2]
'Pauli Murray'

Try it! < / >

What happens if you change the index number to 1? What about 3? 2.0?


# Try out using different index numbers

Lists can also contain other lists. To retrieve a value from a list within a list, we use two indexes (or indices).

# Retrieving an item from a list within a list
my_inspirations = [['Harriet Tubman', 'Rosa Parks', 'Pauli Murray'], ['Martin Luther King Jr.', 'Frederick Douglass', 'Malcolm X']]
my_inspirations[0][2]
'Pauli Murray'

Try it! < / >

Can you change the index for my_inspirations to retrieve 'Malcolm X'?


# Try retrieving Malcolm X from the my_inspirations list

We can also select items from a list beginning from the end/right side of a list by using negative index numbers.

# Retrieving an item from the end of a list by using negative indices
my_inspirations = ['Harriet Tubman', 'Rosa Parks', 'Pauli Murray']
my_inspirations[-1]
'Pauli Murray'

It is not uncommon for lists to be hundreds or thousands of items long. It would be a chore to count all those items to create a slice. If you want to know the length of a list, you can use the len() function.

# Using the len() function to discover the number of items in the list
staff = ['Aaron Aston',
         'Brianna Barton',
         'Carla Cameron',
         'Delia Darcy',
         'Evelyn Elgin',
         'Frederick Federov',
         'Gaston Garbo']
len(staff)
7

Slicing a list#

We can also retrieve a group of consecutive items from a list using slices instead of a single index number. We create a slice by indicating a starting and ending index number. The slice is a smaller list containing all the items between our starting and stopping index number.

# Taking a slice of a list
staff = ['Aaron Aston',
         'Brianna Barton',
         'Carla Cameron',
         'Delia Darcy',
         'Evelyn Elgin',
         'Frederick Federov',
         'Gaston Garbo']
staff[1:3]
['Brianna Barton', 'Carla Cameron']

Notice in our slice that the second index in a slice is the stopping point. That is our return list contains staff[1] ('Brianna Barton') and staff[2] ('Carla Cameron'), but it does not include staff[3] ('Delia Darcy'). This can be confusing if you were expecting three items instead of two. One way to remember this is by subtracting the indexes in your head (3 - 1 = 2 items).

The staff list is 7 items long, meaning the whole list is within the slice staff[0:7]. When we take a slice of a list we can also leave out the first index number (0 is assumed) or the stopping index number (the last item is assumed).

# Taking a slice of a list without a beginning index
staff = ['Aaron Aston',
         'Brianna Barton',
         'Carla Cameron',
         'Delia Darcy',
         'Evelyn Elgin',
         'Frederick Federov',
         'Gaston Garbo']
staff[:5]
['Aaron Aston',
 'Brianna Barton',
 'Carla Cameron',
 'Delia Darcy',
 'Evelyn Elgin']

Try it! < / >

Can you take a slice from the staff list without using a an ending index number? What if we don’t use a starting or ending index?


# Try slicing the staff list without an ending index? What about no starting or ending index?

The in and not in Operators#

If we have a long list, it may be helpful to check whether a value is in the list. We can do this with the in and not in operators, which return a boolean value: True or False.

# Checking whether an item is in a list using the `in` operator

# Create a list called `staff`
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen',
 'Jacqueline Gallagher',
 'Carlos Mcdowell',
 'Jeffrey Harris',
 'Danielle Griffith',
 'Sarah Craig',
 'Vernon Vasquez',
 'Anthony Burton',
 'Erica Bryant',
 'Patricia Walker',
 'Karen Brown',
 'Terri Walker',
 'Michelle Knight',
 'Kathleen Douglas',
 'Debbie Estrada',
 'Jennifer Brewer',
 'Taylor Rodriguez',
 'Lisa Turner',
 'Julie Hudson',
 'Christina Cox',
 'Nancy Patrick',
 'Rita Mosley',
 'Nicholas Gordon',
 'Wanda Vasquez',
 'Jason Lopez',
 'Anna Powers',
 'Tyler Perez']

# Check whether a name is in staff
'Patricia Walker' in staff
True

Try it! < / >

Is Rita McDowell in staff? What about Erica Bryant?


# Check if Rita McDowell and Erica Bryant are in staff

We can change the value of any item in a list using an assignment statement that contains the item’s index number.

# Changing the value of an item in a list
staff = ['Tara Richards', 'Tammy French', 'Justin Douglas']
print(staff)

# Changing an item using an assignment state with index number
staff[1] = 'Tammy Simons'
print(staff)
['Tara Richards', 'Tammy French', 'Justin Douglas']
['Tara Richards', 'Tammy Simons', 'Justin Douglas']

Now we know how to change an item in a list. And can use the in and not in operator to determine if an item is in the list. But if we don’t know the index number of the item, we won’t know which index number to change. We need a way to pass both the name of the list and the name of the item simultaneously to a function. To do that, we’ll use a special kind of function called a method.

List Methods#

A method is a kind of function. (Remember, functions end in parentheses.) Methods, however, act on objects (like lists) so they have a slightly different written form. We will take a look at five useful methods for working with lists.

Method Name

Purpose

Form

index()

search for an item in a list and return the index number

list_name.index(item_name)

append()

add an item to the end of a list

list_name.append(item_name)

insert()

insert an item in the middle of a list

list_name.insert(index_number, item_name)

remove()

remove an item from a list based on value

list_name.remove(‘item_value’)

sort()

sort the order of a list

list_name.sort()

The index() Method#

The index() method checks to see if a value is in a list. If the value is found, it returns the index number for the first item with that value. (Keep in mind, there could be multiple items with a single value in a list). If the value is not found, the index() method returns a ValueError.

# Using the index() method to return the index number of an item by passing a value
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

# Find the index number of a list item
staff.index('Jessica Lee')
12

Try it! < / >

What is the index number of Lisa Grant in staff?


Lists can contain multiple identical items. If there are multiple identical items, we need to use some flow control to return all the indices. The enumerate() function allows us to keep track of the index and element at the same time. Notice that this for loop defines two variables. The first variable keeps track of the current index number in the loop, the second variable keeps track of the value for the current element.

# Getting all indices for items that repeat

staff = ['Tara Richards',
 'John Smith',
 'Justin Douglas',
 'Lauren Marquez',
 'John Smith']

# Use the enumerate function
for index, name in enumerate(staff):
    if name == 'John Smith':
        print(index)
1
4

The append() Method#

The append() method adds a value to the end of a list.


Try it! < / >

Can you add your name to staff?


# Using the append() method to add an item to the end of a list
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

# Append a staff member to the list


# Prints `staff` in a vertical list format to check that the name was added. 
# The list() function will print our list in an easier to read format than the print() function.
list(staff) 
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

We can also add an item to the end of a list by using an assignment statement.

# Adding an item to a list using an assignment statement
# We are concatenating two lists

staff = staff + ['Dustin Henderson'] # Concatenate staff list with the list ['Dustin Henderson']
list(staff)
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen',
 'Dustin Henderson']

The insert() Method#

The insert() method is similar to append() but it takes an argument that lets us choose an index number to insert the new item.

# Using the insert() method to add an item at a specific index number
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

staff.insert(5, 'Arya Stark') # Insert the name 'Arya Stark' at index 5 (The sixth name on the list)
list(staff) # Prints `staff` to check that the name was added at the right spot
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Arya Stark',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

Try it! < / >

Can you make your name the third item on staff?


# Add your name to the staff list


# Show the new staff list after your addition
list(staff)
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Arya Stark',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']

The remove() Method#

The remove() method removes the first item from the list that has a matching value.

# Using the remove() method to remove the first item with a matching value
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']
# Write your remove statement under this comment
staff.remove('Richard Pearson')
# Print `staff` to check that the name was removed
list(staff) 
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Glenn Allen']

Try it! < / >

Can you remove Glenn Allen from staff?


# Remove Glenn Allen from the staff list


# Show the staff list again to confirm the change was made
list(staff)
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Glenn Allen']

Like the .index() method, the .remove() only works on the first item it finds in the list. If there are repeating items on the list, you can use some flow control to make sure you remove them all.

# Removing an item that appears multiple times on the list

staff = ['John Smith',
 'Lauren Marquez',
 'John Smith']

# Use a while loop for flow control
while 'John Smith' in staff:
    staff.remove('John Smith')

# List the staff members after the removal
list(staff)
['Lauren Marquez']

If you know the value you wish to remove then the remove() method is the best option. If you know the index number of the item, you can use a del statement to delete list items.

# Using a `del` statement to delete a list item
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']
del staff[-1] # Delete the final item in the list. In this case, 'Glenn Allen'.
list(staff)
['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson']

The sort() Method#

The sort() method sorts a list in alphabetical order, where strings with capital letters are sorted A-Z, then strings with lowercase letters are sorted A-Z.

# Using the `sort()` method to sort a list in alpha-numeric order
staff = ['Tara Richards',
 'Tammy French',
 'Justin Douglas',
 'Lauren Marquez',
 'Aaron Wilson',
 'Dennis Howell',
 'Brandon Reed',
 'Kelly Baker',
 'Justin Howard',
 'Sarah Myers',
 'Vanessa Burgess',
 'Timothy Davidson',
 'Jessica Lee',
 'Christopher Miller',
 'Lisa Grant',
 'Ryan Chan',
 'Gary Carson',
 'Anthony Mitchell',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Rachel Gonzalez',
 'Andrew Clark',
 'Richard Pearson',
 'Glenn Allen']
staff.sort()
list(staff)
['Aaron Wilson',
 'Andrew Clark',
 'Anthony Mitchell',
 'Brandon Reed',
 'Christopher Miller',
 'Dennis Howell',
 'Gary Carson',
 'Glenn Allen',
 'Jacob Turner',
 'Jennifer Bonilla',
 'Jessica Lee',
 'Justin Douglas',
 'Justin Howard',
 'Kelly Baker',
 'Lauren Marquez',
 'Lisa Grant',
 'Rachel Gonzalez',
 'Richard Pearson',
 'Ryan Chan',
 'Sarah Myers',
 'Tammy French',
 'Tara Richards',
 'Timothy Davidson',
 'Vanessa Burgess']

Try it! < / >

The sort() method can take the argument reverse=True. Try applying it to the sort() method above. What does it do?


# Try out sorting in reverse order

Iterate through a list with a for loop#

We can use a for loop to iterate through all the items in a list. The for loop will create a new temporary variable to store the current item in the list (no assignment statement required).

# Using a for loop with a list
for person in staff: # Whatever is after `for` becomes the temporary variable
    print(person)
Aaron Wilson
Andrew Clark
Anthony Mitchell
Brandon Reed
Christopher Miller
Dennis Howell
Gary Carson
Glenn Allen
Jacob Turner
Jennifer Bonilla
Jessica Lee
Justin Douglas
Justin Howard
Kelly Baker
Lauren Marquez
Lisa Grant
Rachel Gonzalez
Richard Pearson
Ryan Chan
Sarah Myers
Tammy French
Tara Richards
Timothy Davidson
Vanessa Burgess

Coding Challenge! < / >

Using your knowledge of flow control statements and lists, can you solve the following challenges? To complete these challenges, we will use a list called ranking based on FIFA’s rankings of the Women’s National Teams before the World Cup.


# Level 1 Challenge
# The data has some errors in it. Correct the following errors:
# Correct the spelling of Canada in the rankings
# Remove Uruguay from the rankings and add Australia at the bottom
# Add England to the rankings after Sweden

ranking = ['USA',
           'Germany',
           'Sweden',
           'France',
           'Uruguay',
           'Spain',
           'Canda',
           'Brazil',
           'Netherlands',]
# Level 2 Challenge
# Write a program that lets the user input any country and check if they are in the top ten ranking
ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']
# Level 3 Challenge
# Write a program that lets a user input a country and receive their rank

ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']
# Level 4 Challenge
# Write a program that lets a user input a country and return all the teams with a higher rank
ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']

Dictionaries#

Like a list, a dictionary can hold many values within a single variable. We have seen that the items of a list are stored in a strictly-ordered fashion, starting from item 0. In a dictionary, each value is stored in relation to a descriptive key forming a key/value pair. Technically, as of Python 3.7 (June 2018), dictionaries are also ordered by insertion. In practice, however, the most useful aspect of a dictionary is the ability to supply a key and receive a value without reference to indices. Whereas a list is typed with brackets [], a dictionary is typed with braces {}. The key and/or value can be an integer, float, or string.

example_dictionary = {key1 : value1, key2 : value2, key3 : value3}

# An example of a dictionary storing names and occupations
contacts ={
 'Amanda Bennett': 'Engineer, electrical',
 'Bryan Miller': 'Radiation protection practitioner',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Stephanie Petty': 'Architect'}
from pprint import pprint # We import the pretty print function which prints out dictionaries in a neater fashion than the built-in print() function
pprint(contacts) # Use the pretty print function to print `contacts`
{'Amanda Bennett': 'Engineer, electrical',
 'Bryan Miller': 'Radiation protection practitioner',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Stephanie Petty': 'Architect'}

We can add a new key/value pair to our dictionary using an assignment statement.

# Adding the key 'Mirza, Rafia' with the value 'Digital Scholarship Librarian' to the dictionary contact
contacts['Rafia Mirza'] = 'Digital Scholarship Librarian'

pprint(contacts) # Use the pretty print function to print `contacts`
{'Amanda Bennett': 'Engineer, electrical',
 'Bryan Miller': 'Radiation protection practitioner',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Rafia Mirza': 'Digital Scholarship Librarian',
 'Stephanie Petty': 'Architect'}

Try it! < / >

Can you add your name to the contacts dictionary?


Similar to deleting an item from a list, we can use a del statement to delete a key/value pair. We do not need to worry about duplicates because every key in a dictionary must be unique.

# Deleting a key/value pair from the dictionary contacts
del contacts['Bryan Miller'] 

pprint(contacts) # Use the pretty print function to print `contacts`
{'Amanda Bennett': 'Engineer, electrical',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Rafia Mirza': 'Digital Scholarship Librarian',
 'Stephanie Petty': 'Architect'}

Dictionary Methods#

We’ll take a look at five useful methods for working with dictionaries: update(), keys(), values(), items(), and get().

Method Name

Purpose

Form

update()

add new key/value pairs to a dictionary

dict_name.update({key1:value1, key2:value2})

 

combine two dictionaries

dict_name.update(dict_name2)

keys()

check if a key is in a dictionary (True/False)

key_name in dict_name.keys()

 

Loop through the keys in a dictionary

for k in dict.keys():

values()

check if a value is in a dictionary (True/False)

value_name in dict_name.values()

 

Loop through the values in a dictionary

for v in dict.values():

items()

Loop through the keys and values in a dictionary

for k, v in dict.items():

get()

retrieve the value for a specific key

dict_name.get(key_name)

The update() Method#

The update() method is useful for adding many key/value pairs to a dictionary at once. The update() method accepts a single key/value pair, multiple pairs, or even other dictionaries.

# Add a single key/value pair to the dictionary contacts using the update() method
contacts.update(
    {'Rafia Mirza'': 'Digital Scholarship Librarian'}
)

pprint(contacts) # Use the pretty print function to print `contacts`
  Cell In[35], line 3
    {'Rafia Mirza'': 'Digital Scholarship Librarian'}
                      ^
SyntaxError: invalid syntax
# Adding several key/value pairs to the dictionary contacts using the update() method
contacts.update(
    {"Matt Lincoln": "Software Engineer",
     'Ian DesJardins': 'Software Engineer',
    'Zhuo Chen': 'Text Analysis Instructor'}
)

pprint(contacts) # Use the pretty print function to print `contacts`

The keys() and values() Methods#

The keys(), values(), and items() methods are useful for when checking whether a particular key or value exists in a dictionary. We can pair them with in or not in operators to check whether a value is in our dictionary (just like we did with lists).

# Checking if a key is in the contacts dictionary
# Do I know a Noah Delgado?
'Noah Delgado' in contacts.keys()
# Checking if a value is in the contacts dictionary
# Do I know an Architect?
'Architect' in contacts.values()

The get() Method#

If we are sure a key exists, we can return the corresponding value using:

dict_name[key_name]

# Return a value for a particular key
contacts['Noah Delgado']

However, if the key](https://constellate.org/docs/key-terms/#key-value-pair) is not found, the result will be a KeyError.

# Asking for a key that does not exist
contacts['Mickey Mouse']

The more robust approach is to use the get() method. If the key is not found, the None value will be returned. (Optionally, we can also specify a default message to return.)

dict_name.get('key_name', 'key_not_found_message')

# Using the get() method to retrieve the value for the key 'Marissa Munoz'
contacts.get('Marissa Munoz')

Combining keys(), values(), and items() with Flow Control Statements#

It is often usful to combine for loops with the keys(), values(), or items() methods to repeat a task for each entry in a dictionary. We have the following options:

  • .keys() iterates through only the dictionary keys

  • .values() iterates through only the dictionary values

  • .items() iterates through the keys and values

Just like a list for loop, a temporary variable will be created based on whatever name comes after for.

# Print every key in our contacts dictionary
for name in contacts.keys(): # The variable `name` could be any variable name we choose
    print(name)
# Print every value in our contacts dictionary
for occupation in contacts.values(): # The variable `occupation` here could be any variable name we choose
    print(occupation)

If we use the .items() method, we need to define two variable names. It is valid Python to define two variables at once.

# Define two variables at once in Python and assign two strings
word1, word2 = 'Python', 'Basics'

# Verify the variables have been properly assigned
print(word1)
print(word2)
# Print every key and value in our contacts dictionary
for name, occupation in contacts.items():
    print(f'{name} has the job: {occupation}')

Coding Challenge! < / >

Using your knowledge of flow control statements and dictionaries, can you write a program that lists all the architects in your contacts? Check the end of this notebook for possible solutions.


# Level 1 Challenge
# A challenge to search a contacts dictionary and output any individuals who are architects. The result
# should contain the name of any contacts who are architects.

contacts ={
 'Amanda Bennett': 'Engineer, electrical',
 'Bryan Miller': 'Radiation protection practitioner',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Stephanie Petty': 'Architect'}

# Write your solution here. Example solutions at the end of this notebook.
# Level 2 Challenge
# From the dictionary called contacts, create a Python list called `leads` containing the names of people 
# who are architects, translators, or media planners.

Attribution Creative Commons CC BY License

Created by Nathan Kelber and Ted Lawless for JSTOR Labs under Creative Commons CC BY License

Coding Challenge! Solutions#

# Level 1 Solution
# Correct the errors in the ranking list

# Create the list
ranking = ['USA',
           'Germany',
           'Sweden',
           'France',
           'Uruguay',
           'Spain',
           'Canda',
           'Brazil',
           'Netherlands',]

# Correct the spelling of Canada
ranking[6] = 'Canada'

# Remove Uruguay and add Australia
if 'Uruguay' in ranking:
    ranking.remove('Uruguay')

ranking.append('Australia')

# Add England after Sweden
if 'Sweden' in ranking:
    england_index = ranking.index('Sweden') + 1
    ranking.insert(england_index, 'England')
# Level 2 Solution
# Write a program that lets the user input any country and check if they are in the top ten ranking

# Create the ranking list
ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']

# Get the country from the user
country = input('Which country are you interested in? ')

if country in ranking:
    print(f'{country} is in the top ten!')
else:
    print(f'{country} is not in the top ten.')
# Level 3 Solution
# Write a program that lets a user input a country and receive their rank

# Create the ranking list
ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']

# Get the country from the user
country = input('Which country are you interested in? ')

if country in ranking:
    rank = ranking.index(country) + 1
    print(f'{country} is ranked {rank}')
else:
    print(f'{country} is not in the top ten.')
# Level 4 Solution
# Write a program that lets a user input a country and return all the teams with a higher rank

# Create the ranking list
ranking = ['USA',
 'Germany',
 'Sweden',
 'England',
 'France',
 'Spain',
 'Canada',
 'Brazil',
 'Netherlands',
 'Australia']

# Get the country from the user
country = input('Which country are you interested in? ')

if country in ranking:
    index = ranking.index(country)
else:
    index = None
    print('That country is not in the top ten.')

if index != None:
    print('These countries have a higher rank:')
    for each_country in ranking[:index]:
        print(each_country)

Dictionaries Challenge Level 1#

# Level 1 Challenge Solution
# A challenge to search a contacts dictionary and output any individuals who are architects. The result
# should contain the name of any contacts who are architects.

contacts ={
 'Amanda Bennett': 'Engineer, electrical',
 'Bryan Miller': 'Radiation protection practitioner',
 'Christopher Garrison': 'Planning and development surveyor',
 'Debra Allen': 'Intelligence analyst',
 'Donna Decker': 'Architect',
 'Heather Bullock': 'Media planner',
 'Jason Brown': 'Energy manager',
 'Jason Soto': 'Lighting technician, broadcasting/film/video',
 'Marissa Munoz': 'Further education lecturer',
 'Matthew Mccall': 'Chief Technology Officer',
 'Michael Norman': 'Translator',
 'Nicole Leblanc': 'Financial controller',
 'Noah Delgado': 'Engineer, land',
 'Rachel Charles': 'Physicist, medical',
 'Stephanie Petty': 'Architect'}

# Write your solution here. Example solutions at the end of this notebook.

for name, occupation in contacts.items():
    if occupation == 'Architect':
        print(name)

Dictionaries Challenge Level 2#

# Level 2 Challenge
# From the dictionary called contacts, create a Python list called `leads` containing the names of people 
# who are architects, translators, or media planners.
leads = []

for name, occupation in contacts.items():
    if occupation == 'Architect' or occupation == 'Translator' or occupation =='Media planner':
        leads.append(name)

print(leads)