10c. Review: Dictionaries#

A review of Chapter 10: Dictionaries, for students who have already studied the chapter. Use the two lists under Concepts covered as a checklist (click a list’s title to hide it), then work through the Questions, which go from the easiest to the hardest. Each question has a suggested answer under Answer. Try the question first, then open the Answer.

Run this page on Colab

Concepts covered#

Questions#

All the questions use only dictionaries, lists, strings, loops, functions and print.

The setup cell below imports math.

# Setup for the questions below (imports, downloads of helper files, ...)
import math

Question 1 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

ages = {'ann': 20, 'bob': 22, 'cy': 19}
print(ages['bob'])
print(len(ages))

Question 2 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

scores = {}
scores['ann'] = 90
scores['bob'] = 85
print(scores)

Question 3 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

prices = {'apple': 2, 'banana': 3}
prices['apple'] = 4
print(prices)

Question 4 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

small = {'a': 1, 'b': 2}
print('a' in small)
print(1 in small)
print(2 in small.values())

Question 5 (very easy): what happens?#

Predict what happens when this code runs, then open the Answer to check.

one = {'a': 1}
print(one['b'])

Question 6 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

original = {'a': 1, 'b': 2}
copy = dict(original)
copy['a'] = 99
print(original)
print(copy)

Question 7 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

letters = {'a': 1, 'b': 2, 'c': 3}
for key in letters:
    print(key)

Question 8 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

numbers = {'a': 1, 'b': 2, 'c': 3}
for value in numbers.values():
    print(value)

Question 9 (very easy): what is displayed?#

Predict what this code displays, then open the Answer to check.

points = {'a': 1, 'b': 2}
for key in points:
    print(key, points[key])

Question 10 (very easy): what is displayed?#

A value in a dictionary can itself be a dictionary. students maps each name to another dictionary, with the student’s age and grade. Predict what this code displays, then open the Answer to check.

students = {'ann': {'age': 20, 'grade': 90}, 'bob': {'age': 22, 'grade': 85}}
print(students['ann']['age'])
print(students['bob']['grade'])

Question 11 (very easy): what is displayed?#

counts.get(key, 0) returns the value for key if the key is in the dictionary, and 0 if it is not. Predict what this code displays, then open the Answer to check.

counts = {'a': 3, 'b': 1}
print(counts.get('a', 0))
print(counts.get('c', 0))

Question 12 (very easy): write a function#

Write a function called lookup_or_zero that takes a dictionary d and a key key, and returns the value for key if key is in the dictionary, and 0 if it is not.

Start from this header (replace ... with the body):

def lookup_or_zero(d, key):
    ...

Examples

print(lookup_or_zero({'a': 1, 'b': 2}, 'b'))
2
print(lookup_or_zero({'a': 1, 'b': 2}, 'c'))
0

Question 13 (very easy): write a function#

Write a function called total_values that takes a dictionary d and returns the sum of its values.

Start from this header (replace ... with the body):

def total_values(d):
    ...

Examples

print(total_values({'a': 1, 'b': 2, 'c': 3}))
6
print(total_values({}))
0

Question 14 (medium): what is displayed?#

Both parts count the letters in 'banana'. Part a uses if and else. Part b does the same count with get (Question 11). Predict what each part displays, then open the Answer to check.

Part a

counter = {}
for letter in 'banana':
    if letter not in counter:
        counter[letter] = 1
    else:
        counter[letter] += 1
print(counter)

Part b

counter = {}
for letter in 'banana':
    counter[letter] = counter.get(letter, 0) + 1
print(counter)

Question 15 (medium): write a function#

Write a function called find_repeats that takes a dictionary of counts — the kind of dictionary the code in Question 14 makes, where each key is a letter and each value is how many times it appears — and returns a list of the keys whose count is greater than 1, in the order they appear in the dictionary.

Start from this header (replace ... with the body):

def find_repeats(counter):
    ...

Examples

print(find_repeats({'b': 1, 'a': 3, 'n': 2}))
['a', 'n']
print(find_repeats({'a': 1, 'b': 1}))
[]

Question 16 (medium): what is displayed?#

The dictionary known stores Fibonacci numbers that have already been computed, so fibonacci_memo does not compute them again. The first two are already in the dictionary: known[0] is 0 and known[1] is 1. Predict what this code displays, then open the Answer to check.

Run this cell to define fibonacci_memo and assign known.

known = {0: 0, 1: 1}

def fibonacci_memo(n):
    if n in known:
        return known[n]
    res = fibonacci_memo(n - 1) + fibonacci_memo(n - 2)
    known[n] = res
    return res
print(fibonacci_memo(5))
print(known)

Question 17 (hard): write a function#

Write a function called merge_counters that takes two dictionaries of counts and returns a new dictionary with the counts from both. For a key that is in both dictionaries, add the two counts.

Start from this header (replace ... with the body):

def merge_counters(c1, c2):
    ...

Examples

print(merge_counters({'a': 2, 'b': 1}, {'a': 1, 'c': 3}))
{'a': 3, 'b': 1, 'c': 3}
print(merge_counters({}, {'x': 5}))
{'x': 5}

Question 18 (hard): write a function#

Write a function called invert that takes a dictionary d and returns a new dictionary with the keys and values swapped: each value of d becomes a key, and each key of d becomes a value.

If two keys have the same value, the second one overwrites the first, so one key is lost. The examples have no repeated values.

Start from this header (replace ... with the body):

def invert(d):
    ...

Examples

print(invert({'a': 1, 'b': 2}))
{1: 'a', 2: 'b'}
print(invert({}))
{}

Question 18b (hard): write a function#

Write a function called invert_keep_all that takes a dictionary d and returns a new dictionary with the keys and values swapped: each value of d becomes a key, and each key of d becomes a value, as in Question 18. If a value appears more than once in d, the key for that value in the new dictionary has a list of the keys that had that value, in the order they appear in d. If a value appears only once, the key has that one key, not a list.

Start from this header (replace ... with the body):

def invert_keep_all(d):
    ...

Examples

print(invert_keep_all({'a': 1, 'b': 2, 'c': 1}))
{1: ['a', 'c'], 2: 'b'}
print(invert_keep_all({'a': 1, 'b': 2}))
{1: 'a', 2: 'b'}
print(invert_keep_all({}))
{}

Question 18c (hard): write a function#

Write a function called invert_to_lists that takes a dictionary d and returns a new dictionary with the keys and values swapped: each value of d becomes a key. Every value in the new dictionary is a list of the keys that had that value, in the order they appear in d. If a value appears only once, its list has one key.

Start from this header (replace ... with the body):

def invert_to_lists(d):
    ...

Examples

print(invert_to_lists({'a': 1, 'b': 2, 'c': 1}))
{1: ['a', 'c'], 2: ['b']}
print(invert_to_lists({'a': 1, 'b': 2}))
{1: ['a'], 2: ['b']}
print(invert_to_lists({}))
{}

Question 19 (hard): write a function#

Write a function called has_duplicates that takes a sequence (a string or a list) and returns True if any element appears more than once, and False if it does not. Use a dictionary to keep track of the elements you have seen.

Start from this header (replace ... with the body):

def has_duplicates(seq):
    ...

Examples

print(has_duplicates('banana'))
True
print(has_duplicates('abc'))
False
print(has_duplicates([1, 2, 3, 2]))
True

Question 20 (hard): write a function#

The dictionary grades maps each student to another dictionary that maps each subject to a grade. Write a function called add_grade that takes grades, a student name, a subject and a grade, and adds the grade. If the student is not in grades yet, first add an empty dictionary for that student.

Start from this header (replace ... with the body):

def add_grade(grades, student, subject, grade):
    ...

Examples

grades = {}
add_grade(grades, 'ann', 'math', 90)
add_grade(grades, 'ann', 'english', 85)
print(grades)
{'ann': {'math': 90, 'english': 85}}
grades = {}
add_grade(grades, 'bob', 'math', 78)
add_grade(grades, 'ann', 'math', 90)
print(grades)
{'bob': {'math': 78}, 'ann': {'math': 90}}

Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International