6Dictionaries and Sets
Objectives
In this chapter, you’ll:
Use dictionaries to represent
pairs.
Add, remove and update a
dictionary’s key–value pairs.
Use dictionary and set
comparison operators.
dictionaries and sets quickly
and conveniently.
Learn how to build dynamic
visualizations and implement
more of your own in the
PyCDS_06_SetsDictionaries.fm Page 1 Tuesday, August 20, 2019 2:32 PM
2Dictionaries and Sets
Exercises
Unless specified otherwise, use IPython sessions for each exercise.
6.1 (Discussion: Dictionary Methods) Briefly explain the operation of each of the fol
lowing dictionary methods:
a) update
Answer: Adds a new key–value pair or updates an existing one if the key is already
b) keys
c) values
d) items
6.2 (What’s Wrong with This Code?) The following code should display the unique
words in the string text and the number of occurrences of each word.
from collections import Counter
text = (‘to be or not to be that is the question’)
counter = Counter(text.split())
for word, count in sorted(counter):
print(f{word:<12}{count})
Answer: sorted(counter) should be sorted(counter.items()); otherwise, a
6.3 (What Does This Code Do?) The dictionary temperatures contains three Fahren-
heit temperature samples for each of four days. What does the for statement do?
temperatures = {
‘Monday’: [66, 70, 74],
‘Tuesday’: [50, 56, 64],
‘Wednesday’: [75, 80, 83],
‘Thursday’: [67, 74, 81]
}
for k, v in temperatures.items():
print(f{k}: {sum(v)/len(v):.2f})
Answer: This code calculates and displays the average temperature for each day:
6.4 (Fill in the Missing Code) In each of the following expressions, replace the ***s
with a set operator that produces the result shown in the comment. The last operation
should check whether the left operand is an improper subset of the right operand. For each
PyCDS_06_SetsDictionaries.fm Page 2 Tuesday, August 20, 2019 2:32 PM
Exercises 3
of the first four expressions, specify the name of the set operation that produces the spec-
ified result.
a) {1, 2, 4, 8, 16} *** {1, 4, 16, 64, 256} # {1,2,4,8,16,64,256}
b) {1, 2, 4, 8, 16} *** {1, 4, 16, 64, 256} # {1,4,16}
c) {1, 2, 4, 8, 16} *** {1, 4, 16, 64, 256} # {2,8}
d) {1, 2, 4, 8, 16} *** {1, 4, 16, 64, 256} # {2,8,64,256}
e) {1, 2, 4, 8, 16} *** {1, 4, 16, 64, 256} # False
Answer:
a) Union:
{1, 2, 4, 8, 16} | {1, 4, 16, 64, 256} # {1,2,4,8,16,64,256}