Programming Fundamentals

Variables, Loops, and Data Structures.


Setting Up Your Programming Environment

  • Python
  • Editor

Installing Python

Currently, the latest version is Python 3.11, but if you have Python 3.9 above, you're good.


Checking If You Have Python Installed

Open up a terminal and try python --version or python3 --version. If you get a version number 3.9 or above, you already have Python installed on your system. If you get a message like command not found, you need to install Python.

To install Python, go to python.org, click on Download and follow the instructions.


VSCode

We use VSCode in this course which is a free editor available for all the major operating systems (Windows, Mac, Linux). You're free to use any editor you already have and feel comfortable with. To install VSCode, go to code.visualstudio.com/download.


Python Shell

You can run snippets of Python code by opening a new terminal window and typing python or python3 (depending on your setup). You get a message like this:

$ python3
Python 3.10.6 (v3.10.6:9c7b4bd164, Aug  1 2022, 17:13:48) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

This command starts a Python terminal session. You should see a Python prompt (>>>), which means your operating system has found the version of Python you just installed.


Running VSCode From the Terminal

You can run VSCode from the terminal by typing code after adding it to the path:

  • Launch VSCode.
  • Open the Command Palette (Cmd+Shift+P or Ctrl+Shift+P on Windows) and type shell command to find the Shell Command: Install 'code' command in PATH command.
  • Restart the terminal for the new Path value to take effect.
  • Now, hopefully!, you should be able to use the code command in your terminal to open VSCode.

Your First (amazing) Python Program

Open an empty folder using VSCode and create file ending in .py. Here, we're going to call it hello_world.py. Add the following code to the file:

print("Hello, World!")

Open up the terminal inside your VSCode using the Ctrl+` or Cmd+` shortcut (or click on the Terminal menu and select New Terminal).

Run the code with the following command:

python hello_world.py

You should be able to see this output:

Hello, World!

Variables & Data Types

We'll talk about different kinds of data you can work with in Python programs. We’ll also learn how to use variables to represent data in our programs.


Variables

In a programming language, a variable is like a container that holds information or data. It has a name and a value, and you can change the value as needed while your program runs.

You can add a variable in Python using variable-name = variable-value. Example:

msg = "Hi, there!"
print(msg)

We’ve added a variable named msg. Every variable is connected to a value, which is the information associated with that variable. In this case the value is the "Hi, there!" text.

Run the program and you should see Hi, there! showing up in the terminal.


Variables

Let's expand the program a little more:

msg = "Hi, there!"
print(msg)

msg = "How's it going?"
print(msg)

Now when you run the program, you should see:

Hi, there!
How's it going?

You can change the value of a variable in your program at any time, and Python will always keep track of its current value.


Variable Names

  • (Rule): Variable names can contain only letters, numbers, and underscores (_). They can start with a letter or an underscore, but not with a number. For instance, you can call a variable message_1 but not 1_message.
  • (Rule): Spaces are not allowed in variable names, but underscores can be used to separate words in variable names. For example, greeting_message works but greeting message will cause errors.
  • (Rule): Avoid using Python keywords and function names as variable names. For example, do not use the word print as a variable name; Python has reserved it for a particular programmatic purpose. (We'll see lots of them in this course!). Tip: using a good editor like VSCode helps you identify such issues.
  • (Best Practice): Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name. In our hello_world.py program, I named the variable msg. It would've been better if I'd named it message!

On Naming Things

There are only two hard things in Computer Science: cache invalidation and naming things.

-- Phil Karlton


In case you're interested, read Naming Things: The Hardest Problem in Software Engineering by Tom Benner.


Think of Variables As Labels

Think of variables as labels that you can assign to values. You can also say that a variable references a certain value.


Strings

The first data type we'll discuss is a string. A string is a series of characters. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your strings like this:

"This is a string."
'This is also a string.'

This flexibility allows you to use quotes and apostrophes within your strings:

'As master Yoda says, "Do or Do not. There is no try!"'

String Methods

A method is an action that Python can perform on a piece of data. Depending on the type of the data, some methods are available and some are not. Some methods come pre-baked with every installation of Python, and you also have the ability to create your own.

Here are some methods for the string data type that come with the Python standard library:

name = "steve jobs"
print(name.title()) # "Steve Jobs"
print(name.upper()) # "STEVE JOBS"

Every method is followed by a set of parentheses, because methods often need additional information to do their work. That information is provided inside the parentheses. The title() and upper() methods don’t need any additional information, so the parentheses are empty.


Using Variables in Strings

In some situations, you’ll want to use a variable’s value inside a string. For example, you might want to use two variables to represent a first name and a last name, respectively, and then combine those values to display someone’s full name:

first_name = "Sherlock"
last_name = "Holmes"

full_name = f"{first_name} {last_name}"
print(full_name) # "Sherlock Holmes"

These strings are called f-strings. The f is for format, because Python formats the string by replacing the name of any variable in braces with its value.


Adding Whitespace to Strings

In programming, whitespace refers to any nonprinting characters, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read.

To add a tab to your text, use the character combination \t. To add a newline in a string, use the character combination \n:

print("Python") # Python
print("\tPython") #     Python
print("\tPy\nthon")
#   Py
#thon

You can also combine them together: \n\t.


Stripping Whitespace

Extra whitespace could be confusing to a program. Although we may consider hello and hello to be the same, to a Python program (or any other program in that matter) they are different. (try "hello" == "hello " in a Python shell). To get rid of the extra whitespace in a string, we can use the lstrip(), rstrip(), and strip() methods:

name = " Python    "
print(name.lstrip()) # will print "Python    "
print(name.rstrip()) # will print " Python"
print(name.strip()) # will print "Python"

TRY IT YOURSELF

  1. Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case.

  2. Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:

    Masoud Karimi once said, “TED talks are highly overrated.”

  3. Repeat the previous exercise, but this time, represent the famous person’s name using a variable called famous_person. Then compose your message and represent it with a new variable called message. Print your message.


TRY IT YOURSELF

  1. Use a variable to represent a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, \t and \n, at least once.

  2. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().


Numbers

Numbers are used quite often in programming. Python treats numbers in several different ways, depending on how they’re being used.


Integers

Integers are numbers without a decimal point, such as 6 and 110. Python supports Integers and arithmetic operations on them:

>>> 2 + 3
5
>>> 3 * 2
6

Python treats ** as the exponent operator:

>>> 3 ** 2
9
>>> 3 ** 3
27

Floats

Python calls any number with a decimal point a float. This term is used in most programming languages, and it refers to the fact that a decimal point can appear at any position in a number. You can perform arithmetic with floats just as well:

>>> 0.2 + 0.2
0.4
>>> 2 * 0.1
0.2

Sometimes, however, you may get weird results like this:

>>> 0.2 + 0.1
0.30000000000000004

Integers vs Floats

When you divide any two numbers, you'll get a float, even if the result is a whole number, unless you use the integer division operator //:

>>> 9/3
3.0
>>> 9//3
3
>>> 9//4
2

Mixing integers with floats will also get you a float:

>>> 2 + 2.0
4.0

Underscores

You can group digits together to make them more readable using _s. Python ignores _s in numbers, they're just for readability:

print(1_000_000) # prints 1000000

None

In Python, None is a special data type that represents the absence of a value or the lack of a specific object. It is often used to indicate that a variable or a function should have a value, but no actual value has been assigned or returned.


Multiple Assignments

You can assign values to more than one variable using just a single line of code. This can help shorten your programs and make them easier to read:

first_name, last_name = "Ada", "Lovelace"

Best Practice: Do not use this method to initialize more than 3 or 4 variables at once.

Best Practice: Limit your lines in a Python program to ~80 characters long.


Constants

A constant is a variable whose value stays the same throughout the life of a program. Python doesn’t have built-in constant types (unlike some other programming languages like C or Go), but Python programmers use all capital letters to indicate a variable should be treated as a constant and never be changed:

PI = 3.14
GREATEST_MOVIE_OF_ALL_TIME = "Interstellar"
INSTRUCTOR_BIRTHDAY = "09/09"

Comments

Comments allow you to add information about why you do things in a certain way in your program. They are not executed and have no impact on the way the program runs. As far as the machine is concerned, they're not there.

In Python, the hash mark (#) indicates a comment. Anything following a hash mark in your code is ignored by the Python interpreter:

# this is a comment and has no effect on the program execution
print("this is not a comment")

"""
This is 
a multiline 
comment
"""

Comments

The real purpose of comments is to explain why you did something, when the reason isn’t obvious. You generally should not add comments that say what a piece of code is doing. That should be obvious from reading the code.

-- Max Alexander

Bad comment:

# integer division
result = total_price // number_of_items

Good comment:

# database schema only accepts integers
result = total_price // number_of_items

The Zen of Python

Experienced Python programmers will encourage you to avoid complexity and aim for simplicity whenever possible. The Python community’s philosophy is contained in “The Zen of Python” by Tim Peters.

Try import this in a Python shell to get the full list.


Lists

A list is a collection of items in a particular order. We use lists when we want to store multiple values in one variable and the order of the items also matters.

You can put anything in a Python list. That is, the items don't have to be of the same type.

Best Practice: Because a list usually contains more than one element, it’s a good idea to make the name of your list plural, such as names or movies.

In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas:

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
print(movies) # ['Interstellar', 'V for Vendetta', 'Django Unchained']

Accessing Elements in a List

You can access any element in a list by telling Python the position, or index, of the item desired. The index of the first item in a list is 0 and not 1. This is not MATLAB!

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
print(movies[0]) # prints 'Interstellar'
print(movies[1]) # prints 'V for Vendetta'
print(movies[3]) # prints ?? Try it yourself

print(movies[-1]) # prints 'Django Unchained' or LAST element of the list
print(movies[-2]) # prints 'V for Vendetta' or SECOND LAST element of the list

print(f"My favourite movie is {movies[0]}.")

Changing Elements in a List

The syntax for modifying an element is similar to the syntax for accessing an element in a list. To change an element, use the name of the list followed by the index of the element you want to change, and then provide the new value you want that item to have:

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
print(movies[0]) # prints 'Interstellar'

movies[0] = "Lord of the Rings"
print(movies[0]) # prints 'Lord of the Rings'

Adding Elements to a List

You can append or insert new elements (or items) to a list. append will add a new element to the end of a list, whereas insert can add a new element at any index (or position) of a list:

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
movies.append("The Matrix")
print(movies) # ['Interstellar', 'V for Vendetta', 'Django Unchained', 'The Matrix']

movies.insert(1, "Kill Bill")
# ['Interstellar', 'Kill Bill', 'V for Vendetta', 'Django Unchained', 'The Matrix']

Best Practice: Because insert usually requires shifting, it's slower than append. Use append if either works for you.


Removing Elements from a List

If you know the position of the item you want to remove from a list, you can use the del statement:

students = ['Alice', 'John', 'Mary']

# let's say Alice drops the course
del students[0]
print(students) # ['John', 'Mary']

Gotcha: When you use del, you lose the element you deleted from the list, which may not be what you wanted!


Removing Elements from a List (more gracefully)

Sometimes you’ll want to use the value of an item after you remove it from a list. For example, you want to remove a student from the class list when they drop the course, but you also want to give them their class fee back and send them a confirmation email afterward:

students = ['Alice', 'John', 'Mary']

# let's say Alice drops the course
dropped_student =  students.pop(0)
print(students) # still prints out ['John', 'Mary']

refund_student(dropped_student)
send_confirmation(dropped_student)

pop() without any arguments will remove the last element of the list.


Removing Based on Value

You can remove the first occurance of a value from a list using the remove() method:

students = ['Alice', 'John', 'Mary']

# let's say Alice drops the course
students.remove('Alice')
print(students) # ['John', 'Mary']

TRY IT YOURSELF

  • Try removing a non-existing element from a list. What do you think would happen?
students = ['Alice', 'John', 'Mary']
students.remove('Steve')

Sorting a List

You can sort a list using both sort() and sorted() methods.


Sorting a List

sort() changes the original list, whereas sorted() leaves it untouched (unless you want to change that).

grades = [12, 20, 35, 8, 120]
grades.sort()
print(grades) # [8, 12, 20, 35, 120]

# now with sorted
grades = [12, 20, 35, 8, 120]
sorted(grades)
print(grades) # [12, 20, 35, 8, 120]

grades = sorted(grades)
print(grades) # [8, 12, 20, 35, 120]

Sorting a List

You can use reverse=True argument in both sort() and sorted() to change the order of sorting.

grades = [12, 20, 35, 8, 120]
grades.sort(reverse=True)
print(grades) # [120, 35, 20, 12, 8]

grades = sorted(grades, reverse=True)
print(grades) # [120, 35, 20, 12, 8]

Reversing a List

You can use the reverse() method to reverse a list. Note that reverse() doesn't perform any sorting; it simply reverses the order of the list (and changes the original list!).

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
movies.reverse()
print(movies) # ['Django Unchained', 'V for Vendetta', 'Interstellar']

Finding the Length of a List

You can quickly find the length of a list by using the len() function.

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
print(len(movies)) # 3

TRY IT YOURSELF

Think of at least five places in Calgary you’d like to visit.

  • Store the locations in a list. Make sure the list is not in alphabetical order.
  • Print your list in its original order. Don’t worry about printing the list neatly; just print it as a raw Python list.
  • Use sorted() to print your list in alphabetical order without modifying the actual list.
  • Show that your list is still in its original order by printing it.
  • Use sorted() to print your list in reverse-alphabetical order without changing the order of the original list.
  • Show that your list is still in its original order by printing it again.
  • Use reverse() to change the order of your list. Print the list to show that its order has changed.
  • Use reverse() to change the order of your list again. Print the list to show it’s back to its original order.
  • Use sort() to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed.
  • Use sort() to change your list so it’s stored in reverse-alphabetical order. Print the list to show that its order has changed.

Looping Through a List

You often need to run through all elements in a list and perform a the same task on all of them, such as sending an email to every person in a list. You can use Python’s for loop to do that.

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
for movie in movies:
    print(movie)

The output will be:

Interstellar
V for Vendetta
Django Unchained

What's movie in the above code?


Looping Through a List

You can do more stuff inside a loop:

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
for movie in movies:
    print(f"The movie name is {movie}")
    print(f"I like to see {movie}")
print("This line will only run once and not per element in the list")

Every indented line following the line for movie in movies is considered inside the loop, and each indented line is executed once for each value in the list. Any lines of code after the for loop that are not indented are executed once without repetition.


Indentation in Python

Python uses indentation to determine how a line, or group of lines, is related to the rest of the program. In the previous examples, the lines that printed messages to individual movies were part of the for loop because they were indented. Python’s use of indentation makes code very easy to read.


Indentation Errors

Always indent the line after the for statement in a loop.

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
for movie in movies:
print(f"The movie name is {movie}")

Indentation Errors

Remember to indent all lines that belong to a code block (such as a for loop).

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
for movie in movies:
    print(f"The movie name is {movie}")
print(f"I like to see {movie}")

What's the output of the above code?


Indentation Errors

Unnecessary indentation:

message = "Hello!"
    print(message)

TRY IT YOURSELF

  • Store a few topics you'll learn in this course (SSD 101) in a list (such as Git, Programming Fundamentals, Testing, and Algorithms). Write a Python program that runs through the list and for each item prints I'm going to learn <topic> in SSD 101.

The range() function

Python’s range() function makes it easy to generate a series of numbers.

for number in range(1, 5):
    print(number)

Output:

1
2
3
4

The first number in range() is inclusive, but the second one exclusive! The first argument is optional. If not specified, range() will start from 0. You can also pass a third argument as a step. Try replacing range(1, 4) with range(1, 4, 2) in the above example.


Make a List of Numbers with range()

You can make a list from the results of range() using the list() function:

even_numbers = list(range(1, 6, 2))
print(even_numbers) # [1, 3, 5] 

TRY IT YOURSELF

  • Write a Python program that computes the square of numbers from 0 to 20, adds them to a list, and prints the list at the end.

Hint:

squares = []
for number in range(0, 21):
    # ...

Fun Methods with a List of Numbers

There are a few Python methods that may come in handy when you're working on a list of numbers:

sales = [120, 45, 67, 350, 599, 1210]
print(min(sales)) # 45
print(max(sales)) # 1210
print(sum(sales)) # 2391

Working with Part of a List

Instead of working with a whole list, you can also work with a specific group of items in a list, called a slice in Python.

To make a slice, you specify the index of the first and last elements you want to work with. As with the range() function, Python stops one item before the second index you specify.

movies = ["Interstellar", "V for Vendetta", "Django Unchained", "Kill Bill"]
print(movies[0:2]) # ['Interstellar', 'V for Vendetta']
print(movies[2:4]) # ['Django Unchained', 'Kill Bill']
print(movies[1:]) # ['V for Vendetta', 'Django Unchained', 'Kill Bill']
print(movies[:3]) # ['Interstellar', 'V for Vendetta', 'Django Unchained']
print(movies[-2:]) # ??

Looping Through a Slice

You can loop through a slice as you would with a whole list:

movies = ["Interstellar", "V for Vendetta", "Django Unchained", "Kill Bill"]
for movie in movies[:2]:
    print(movie)

Tuples

Tuples are like Python lists except that they cannot be changed later. We can't add, remove, or change their items. This is useful if you want to have a list whose items must not change during the program. Use () instead of [] to create a tuple.

movies = ["Interstellar", "V for Vendetta", "Django Unchained"]
print(movies[0]) # Interstellar
movies[0] = "Kill Bill" # this is fine

movies = ("Interstellar", "V for Vendetta", "Django Unchained")
print(movies[0]) # Interstellar
movies[0] = "Kill Bill" # this is NOT fine!

Gotcha: Tuples are technically defined by the presence of a comma. In order to create a tuple with one element, you need to do this:

movies = ("Interstellar", )

Looping Through a Tuple

You can loop through a tuple just like you would for a list:

movies = ("Interstellar", "V for Vendetta", "Django Unchained")
for movie in movies:
    print(movie)

# slicing a tuple
for movie in movies(1:):
    print(movie)

TRY IT YOURSELF

  • What happens if you try to reassign a new tuple to a variable that's already pointing to a tuple?
movies = ("Interstellar", "V for Vendetta", "Django Unchained")
movies = ("Kill Bill",)

Dictionaries

Another complex data type in Python is the Python dictionary. A dictionary is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key (unlike lists where you use an index). A key's value could be any type you can create in Python, such as strings, numbers, lists, dictionaries, etc.

In Python, a dictionary is wrapped in braces ({}) with a series of key-value pairs inside them.

ssd101_subjects = {
    "chapter_1": "Git",
    "chapter_2": "Programming Fundamentals",
    "chapter_3": "Testing"
}
print(ssd101_subjects) 
# {'chapter_1': 'Git', 'chapter_2': 'Programming Fundamentals', 'chapter_3': 'Testing'}

You can have an unlimited number of key-value pairs in a dictionary!


Accessing Values in a Dictionary

To get the value associated with a key, give the name of the dictionary and then place the key inside a set of square brackets:

ssd101_subjects = {
    "chapter_1": "Git",
    "chapter_2": "Programming Fundamentals",
    "chapter_3": "Testing"
}

first_chapter = ssd101_subjects["chapter_1"]
print(f"First, we're going to learn about {first_chapter}. Yoohoooo!!")

TRY IT YOURSELF

  • Try accessing a key that doesn't exist in a dictionary. What do you think would happen?
ssd101_subjects = {
    "chapter_1": "Git",
    "chapter_2": "Programming Fundamentals",
    "chapter_3": "Testing"
}

print(ssd101_subjects["chapter_4"])

Using get() to Access Values

Using keys in square brackets ([]) to retrieve the value you’re interested in from a dictionary might cause one potential problem: if the key you ask for doesn’t exist, you’ll get an error.

get() method to the rescue! The get() method requires a key as a first argument. As a second optional argument, you can pass the value to be returned if the key doesn’t exist. No more errors!

ssd101_subjects = {
    "chapter_1": "Git",
    "chapter_2": "Programming Fundamentals",
    "chapter_3": "Testing"
}

print(ssd101_subjects.get("chapter_4")) # prints None, but no error
print(ssd101_subjects.get("chapter_4", "TBD")) # prints 'TBD'

Adding New Key-Value Pairs

Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time.

ssd101_subjects = {
    "chapter_1": "Git",
    "chapter_2": "Programming Fundamentals",
    "chapter_3": "Testing"
}

ssd101_subjects["chapter_4"] = "Algorithms & Data Structure" 

Good to know: In Python, dictionaries retain the order of keys in which they were defined. (this is a big deal actually!)


An Empty Dictionary

You can start with an empty dictionary and add items as you go furthur in your program. Sometimes this is necessary as you don't know in advance what you'll have in your dictionary. e.g. when you're getting information from an external source.

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9.8
movie_ratings["Lord of the Rings"] = 9.5
print(movie_ratings)
# {'Interstellar': 10, 'V for Vendetta': 9.8, 'Lord of the Rings': 9.5}

Changing an Existing Value in a Dictionary

We can change the value of a key at any time using the key and a new value:

movie_ratings = {}
movie_ratings["Interstellar"] = 10
print(f"IMDB rating of 'Interstellar' is {movie_ratings['Interstellar']}")

movie_ratings["Interstellar"] = 9.8
print(f"IMDB rating of 'Interstellar' is now {movie_ratings['Interstellar']}")

Removing Key-Value Pairs

You can remove a key-value pair using the del statement, like you would with a Python list. del needs the name of the dictionary and the key you want to delete.

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9.8

del movie_ratings["Interstellar"]
print(movie_ratings) # {'V for Vendetta': 9.8}

Looping Through a Dictionary (method 1)

You can run through all key-value pair in a dictionary using the items() method:

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9.8
movie_ratings["Lord of the Rings"] = 9.5

for movie, rating in movie_ratings.items():
    print(f"Movie {movie} has the rating: {rating}.")

# Movie Interstellar has the rating: 10.
# Movie V for Vendetta has the rating: 9.8.
# Movie Lord of the Rings has the rating: 9.5.

Looping Through a Dictionary (method 2)

You can choose to only loop through the keys in a dictionary using the keys() method:

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9.8
movie_ratings["Lord of the Rings"] = 9.5

for movie in movie_ratings.keys():
    print(f"Movie {movie} exists in the dictionary.")

# Movie Interstellar exists in the dictionary.
# Movie V for Vendetta exists in the dictionary.
# Movie Lord of the Rings exists in the dictionary.

Looping Through a Dictionary (still method 2)

Because the keys() method returns a list, you can perform an action on the list of keys in a dictionary before running through them. For example, we can sort the keys alphabetically first:

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9.8
movie_ratings["Lord of the Rings"] = 9.5

for movie in sorted(movie_ratings.keys()):
    print(f"Movie {movie} exists in the dictionary.")

# Movie Interstellar exists in the dictionary.
# Movie Lord of the Rings exists in the dictionary.
# Movie V for Vendetta exists in the dictionary.

Looping Through a Dictionary (method 3)

If you are mainly interested in the values that a dictionary contains, you can use the values() method to return a sequence of values without any keys:

movie_ratings = {}
movie_ratings["Interstellar"] = 10
movie_ratings["V for Vendetta"] = 9
movie_ratings["Lord of the Rings"] = 8

all_ratings = movie_ratings.values()
print(f"Average rating: {sum(all_ratings) / len(all_ratings)}") # Average rating: 9.0

TRY IT YOURSELF

  • Write a Python program that stores the provinces of Canada and their capitals in a dictionary. Run through the dictionary and print out each province with its capital on a separate line.

Nesting

Sometimes you’ll want to store multiple dictionaries in a list, or a list of items as a value in a dictionary. This is called nesting. You can nest dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside another dictionary.


A List of Dictionaries

person_1 = {"name": "Alice", "major": "Software Engineering"}
person_2 = {"name": "John", "major": "Electrical Engineering"}
person_3 = {"name": "Mary", "major": "Mechanical Engineering"}

people = [person_1, person_2, person_3]

for person in people:
    print(f"{person['name']} is taking {person['major']} at U of C.")

# Alice is taking Software Engineering at U of C.
# John is taking Electrical Engineering at U of C.
# Mary is taking Mechanical Engineering at U of C.

A List in a Dictionary

person_1 = {"name": "Alice", "major": "Software ", "grades": ["A", "B+", "A+"]}
print(person_1["grades"]) # ['A', 'B+', 'A+']

person_1 = {"name": "Alice", "major": "Software Engineering", "grades": ["A", "B+", "A+"]}
person_2 = {"name": "John", "major": "Electrical Engineering", "grades": ["A+", "B-", "B+"]}
people = [person_1]
people.append(person_2)

for person in people:
    print(f"Grades for {person['name']}: {person['grades']}.")
# Grades for Alice: ['A', 'B+', 'A+'].
# Grades for John: ['A+', 'B-', 'B+'].

A Dictionary in a Dictionary

students = {
    "Alice": {
        "major": "Software Engineering",
        "grades": ["A", "B+", "A+"]
    },
    "John": {
        "major": "Electrical Engineering",
        "grades": ["A+", "B-", "B+"]
    }
}

for student_name, student_info in students.items():
    print(f"Student {student_name} is taking {student_info['major']} with grades: {student_info['grades']}.")

# Student Alice is taking Software Engineering with grades: ['A', 'B+', 'A+'].
# Student John is taking Electrical Engineering with grades: ['A+', 'B-', 'B+'].

TRY IT YOURSELF

  • Create a phone book in Python using a dictionary. Use names as the keys and a dictionary of information (such as phone number, address, and email) as the value for each person. That is, you should be able to look up Alice in the dictionary and get her phone number, address and email. If the person you're looking for has not yet added to the phone book, the program should show None as their info.