Previous Lecture Lec17 Next Lecture

Lec17, Mon 03/02

Python Dictionaries


Soliving Recursion

Questions to ask to solve recursion

A skeleton of the recursive function

def recF (input):
    if input ...:
        print/return # base case(s)
    else / elif:
        print/return recF (input # --> base case)

Note on Labs:

Lab grades to be released soon, if you did not name your files/functions correctly, Gradescope will give you a 0. Don’t freak out! You can submit a regrade request and Prof. K will rename and reupload you files. Unfortunately, nothing can be done for functions that were not named correctly.

Recursion Practice (slide 11)

Create a recursive function called countdown() that takes a parameter n and recursively counts down from parameter n and recursively counts down from n to 0 (inclusive of both), mirroring the values around the output of 0.

What would our function look like?

Let’s pull up our list of questions: - Our base case is n == 0 - The action that should be taken in our base case is print(n) - The first recursive case is n == 1 - The action that should be taken to get from our first recursive case to the base case is countdown(n-1) - Two parts: action calling the function and an action handling the input itself

Question: Do we need a break after the base case?

Question: What happens if we replace print with return?

Now, let’s move on to countdown_mirror() - Base case doesn’t change - The additional action is the mirroring part

Once you figure out your first recursive case, 99% of the time you’re done!

Slide 16-17:

Question: What if we used a return in this function? a = return countdown_mirror(n-1) ==> Not valid syntax, return is a standalone function

Question: Do I always need to use input == something?

Practice Problem

def countdown(n):
  if n = 0:


A new data structure.

Dictionaries are sometimes referred to as tables or maps

Searching through dictionaries is much faster than lists!

# Demo of the speed difference

In order to get an item out of the list, we need to know the index of the item. For dictionaries, we don’t really care about that. All we need is the key. For example, if we want to print the number of bananas, all we need is the key (banana).

Question: Can we put a dictionary inside of another dictionary?

If we are looking for a key in a dictionary that doesn’t exist in the dictionary, python will gives us a KeyError.

# .get() code

By default, .get() returns None if a key is not present in a dictionary.

We are able to add a key and a corresponding value to our dictionary

Question: how would we reassign a value of an existing key? D['pear'] = 55

from time import perf_counter

What this code is doing:

Once we have our dictionary, sometimes

Notice, the values inside a dictionary are their own type called dict_values

Question: Are the keys or the values the view type?