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.
Concepts covered#
Python Syntax and Semantics
Creating dictionaries
{}is an empty dictionary:len({})is0.This creates a dictionary with three items:
{'zero': 0, 'one': 1, 'two': 2}
Each item is
KEY: VALUE, and items are separated by commas. The keys can be almost any type, and the values can be any type.dict()makes an empty dictionary.dict(DICT)makes a copy ofDICT:dict({'a': 1})is{'a': 1}.
Adding and changing items
This adds a new item to the dictionary:
DICT[KEY] = VALUE
For example, after this code
dis{'a': 1}:d = {} d['a'] = 1
Assigning to a key that is already there replaces its value; it does not add a new item. After this code
dis{'a': 99}:d = {'a': 1} d['a'] = 99
Looking up a value
DICT[KEY]returns the value forKEY:{'a': 1, 'b': 2}['b']is2.Looking up a key that is not in the dictionary is a
KeyError.len(DICT)returns the number of items:len({'a': 1, 'b': 2})is2.
The in operator
KEY in DICTisTrueifKEYis a key in the dictionary:'a' in {'a': 1}isTrue.inchecks keys only, not values:1 in {'a': 1}isFalse.DICT.values()gives the values, soVALUE in DICT.values()checks whether a value is in the dictionary:1 in {'a': 1}.values()isTrue.
The get method
DICT.get(KEY, DEFAULT)returns the value forKEYif it is there, andDEFAULTif it is not:{'a': 1}.get('b', 0)is0.
Looping through a dictionary
This runs the body once for each key in the dictionary, in the order the keys were added:
for KEY in DICT: BODY
This runs the body once for each value:
for VALUE in DICT.values(): BODY
To get the keys and the values, loop through the keys and look up each value with
DICT[KEY].
Lists and dictionaries
A list can be a value:
{'a': [1, 2]}has a list as its value.A list cannot be a key, because a list is mutable and keys must be hashable. Using a list as a key is a
TypeError.A dictionary is mutable, so it can be a value but not a key.
A value can itself be a dictionary:
{'ann': {'age': 20}}is a dictionary with a dictionary as its value. To look up a value in the inner dictionary, use two brackets:{'ann': {'age': 20}}['ann']['age']is20.
The counter pattern
To count how many times each letter appears, use a dictionary that maps each letter to its count. The first time a letter appears, add it with a count of 1; after that, add 1 to its count:
if letter not in counter: counter[letter] = 1 else: counter[letter] += 1
COUNTER[KEY] += 1adds 1 to the value forKEY.
A hash table
A dictionary is a hash table, so looking up a key takes about the same time no matter how many items the dictionary has.
inon a list takes time proportional to the length of the list, so for a long list it is much slower.
Accumulating and filtering
The accumulator pattern: start with an empty list (or 0) and add to it each time through the loop.
Filtering: loop through a sequence and select (or omit) some of its elements.
Memos
A memo is a computed value stored in a dictionary, so it does not have to be computed again. Before computing, check
if N in KNOWN.
Definitions, etc.
Definitions
DEFINITION: A dictionary is an object that contains key-value pairs, also called items.
DEFINITION: An item is, in a dictionary, another name for a key-value pair.
DEFINITION: A key is an object that appears in a dictionary as the first part of a key-value pair.
DEFINITION: A value is an object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word “value”.
DEFINITION: A mapping is a relationship in which each element of one set corresponds to an element of another set.
DEFINITION: A hash table is a collection of key-value pairs organized so that we can look up a key and find its value efficiently.
DEFINITION: A hashable object is one that can be a key in a dictionary. Immutable types like integers, floats and strings are hashable. Mutable types like lists and dictionaries are not.
DEFINITION: A hash function is a function that takes an object and computes an integer that is used to locate a key in a hash table.
DEFINITION: An accumulator is a variable used in a loop to add up or accumulate a result.
DEFINITION: Filtering is looping through a sequence and selecting or omitting elements.
DEFINITION: A call graph is a diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee.
DEFINITION: A memo is a computed value stored to avoid unnecessary future computation.
Other ideas
Do not use
dictas a variable name, because it is the name of a built-in function.When you work with a dictionary, remember that
inchecks keys, not values.Debugging large data sets: scale down the input (start with the first 10 lines, or the smallest example you can find); check summaries and types (for example, the number of items in a dictionary, or the type of a value); write self-checks (a sanity check, which detects results that are “insane”, and a consistency check, which compares the results of two different computations); format the output.
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))
Answer
22
3
Looking up a key gives its value: ages['bob'] is 22, and len(ages) is 3.
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)
Answer
{'ann': 90, 'bob': 85}
The empty dictionary {} has no items. Each assignment adds one item, so after the two assignments scores is {'ann': 90, 'bob': 85}.
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)
Answer
{'apple': 4, 'banana': 3}
Assigning to a key that is already there does not add an item: it replaces the value. So after the assignment prices is {'apple': 4, 'banana': 3}.
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())
Answer
True
False
True
in checks keys, not values. 'a' is a key, so 'a' in small is True. 1 is a value, not a key, so 1 in small is False. .values() gives the values, so 2 in small.values() is True.
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'])
Answer
1 one = {'a': 1}
----> 2 print(one['b'])
KeyError: 'b'
This is a KeyError: there is no key 'b' in the dictionary.
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)
Answer
{'a': 1, 'b': 2}
{'a': 99, 'b': 2}
dict(original) makes a new dictionary with the same items, so changing copy does not change original. After the assignment, original is {'a': 1, 'b': 2} and copy is {'a': 99, 'b': 2}.
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)
Answer
a
b
c
Looping through a dictionary gives its keys, in the order they were added. list(letters) is ['a', 'b', 'c'], so the loop prints a, b and c, each on its own line.
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)
Answer
1
2
3
.values() gives the values, so the loop prints them one per line. list(numbers.values()) is [1, 2, 3].
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])
Answer
a 1
b 2
The loop gives each key, and points[key] looks up its value. points['a'] is 1 and points['b'] is 2, so the first line is a 1 and the second is b 2.
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'])
Answer
20
85
students['ann'] is the dictionary for Ann, so students['ann']['age'] is 20. students['bob']['grade'] is 85.
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))
Answer
3
0
'a' is in the dictionary, so counts.get('a', 0) is 3. 'c' is not, so counts.get('c', 0) is 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
Answer
Use get with a default of 0:
def lookup_or_zero(d, key):
return d.get(key, 0)
Then try: print(lookup_or_zero({'a': 1, 'b': 2}, 'b')).
Or check with in:
def lookup_or_zero(d, key):
if key in d:
return d[key]
return 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
Answer
Start with a total of 0, and add each value to it:
def total_values(d):
total = 0
for value in d.values():
total += value
return total
Then try: print(total_values({'a': 1, 'b': 2, 'c': 3})).
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)
Answer
Part a: The if checks whether the letter is already a key. The first time a letter appears, it is not, so the code adds it with a count of 1. After that, it adds 1 to the count. So counter is {'b': 1, 'a': 3, 'n': 2}.
{'b': 1, 'a': 3, 'n': 2}
Part b: counter.get(letter, 0) returns the count so far, or 0 the first time the letter appears. Adding 1 gives the new count. So counter is {'b': 1, 'a': 3, 'n': 2}.
{'b': 1, 'a': 3, 'n': 2}
Both parts display the same dictionary. Line by line, Part b compared with Part a:
counter = {}— UNCHANGEDfor letter in 'banana':— UNCHANGEDcounter[letter] = counter.get(letter, 0) + 1— CHANGED: this one line replaces the four lines of theifandelse.if letter not in counter:— DELETEDcounter[letter] = 1— DELETEDelse:— DELETEDcounter[letter] += 1— DELETEDprint(counter)— UNCHANGED
What changed: the four lines of the if and else became one line that uses get. What did not change: the dictionary that is counted, the loop, and the output.
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}))
[]
Answer
Loop through the keys, and keep the ones whose count is greater than 1:
def find_repeats(counter):
result = []
for key in counter:
if counter[key] > 1:
result.append(key)
return result
Then try: print(find_repeats({'b': 1, 'a': 3, 'n': 2})).
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)
Answer
5
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
fibonacci_memo(5) is 5. After the call, known holds every Fibonacci number up to 5: known is {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}.
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}
Answer
Start with a copy of the first dictionary, then add each count from the second:
def merge_counters(c1, c2):
result = dict(c1)
for key in c2:
result[key] = result.get(key, 0) + c2[key]
return result
Then try: print(merge_counters({'a': 2, 'b': 1}, {'a': 1, 'c': 3})).
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({}))
{}
Answer
Loop through the keys, and put each value in as a key with the old key as its value:
def invert(d):
result = {}
for key in d:
result[d[key]] = key
return result
Then try: print(invert({'a': 1, 'b': 2})).
If two keys have the same value, the second one overwrites the first, so one key is lost. The examples have no repeated values.
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({}))
{}
Answer
First make a dictionary where every value is a list of the keys that had it. Then replace each list that has one key with that key:
def invert_keep_all(d):
result = {}
for key in d:
value = d[key]
if value in result:
result[value].append(key)
else:
result[value] = [key]
for value in result:
if len(result[value]) == 1:
result[value] = result[value][0]
return result
Then try: print(invert_keep_all({'a': 1, 'b': 2, 'c': 1})).
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({}))
{}
Answer
Build a list of keys for each value, as in Question 18b, but keep every value a list:
def invert_to_lists(d):
result = {}
for key in d:
value = d[key]
if value in result:
result[value].append(key)
else:
result[value] = [key]
return result
Then try: print(invert_to_lists({'a': 1, 'b': 2, 'c': 1})).
Line by line, this answer compared with the answer to Question 18b:
def invert_to_lists(d):— CHANGED: only the name of the function. In Question 18b it isinvert_keep_all.result = {}— UNCHANGEDfor key in d:— UNCHANGEDvalue = d[key]— UNCHANGEDif value in result:— UNCHANGEDresult[value].append(key)— UNCHANGEDelse:— UNCHANGEDresult[value] = [key]— UNCHANGEDfor value in result:— DELETEDif len(result[value]) == 1:— DELETEDresult[value] = result[value][0]— DELETEDreturn result— UNCHANGED
What changed: the name of the function, and the second loop is gone, so nothing is turned back into a single key, and every value stays a list. What did not change: the first loop, which builds the list of keys for each value.
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
Answer
Keep a dictionary of the elements seen so far. If an element is already in the dictionary, it is a repeat:
def has_duplicates(seq):
seen = {}
for element in seq:
if element in seen:
return True
seen[element] = True
return False
Then try: print(has_duplicates('banana')).
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}}
Answer
If the student is not a key yet, add an empty dictionary for that student first; then the subject and grade go into that inner dictionary:
def add_grade(grades, student, subject, grade):
if student not in grades:
grades[student] = {}
grades[student][subject] = grade
Then try: grades = {}, add_grade(grades, 'ann', 'math', 90), add_grade(grades, 'ann', 'english', 85) and print(grades).
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