Skip to content

Week 11: Dictionaries

Submit PA4 to Gradescope

If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.

🎯 Objectives

In Week 9, a set answered one question: is this in here? A dictionary answers a better one: what goes with this? You look a key up the same way you checked membership in a set, but instead of a yes or no, you get the data that belongs to it: a score, a count, a phone number, the patch a square belongs to.

You've used dictionaries since Week 8 to count things. This week fills in the rest: the methods that look things up safely and hand you keys and values together, loops over a dictionary that group and summarize data, and comprehensions, which build a whole list, set, or dictionary in one line.

By the end of the week you should be able to:

  • Use a dictionary to map keys to values, and explain how looking up a key is like checking membership in a set, except that you get back the value that goes with it.
  • Use dictionary methods such as get(), keys(), values(), and items(), and add, replace, and remove entries.
  • Loop over a dictionary's keys, values, or items to group and summarize data.
  • Read and write list, set, and dictionary comprehensions, rewrite a short accumulator loop as one, and say when a plain loop is clearer.

Quiz 4 is this week, and Quiz 5 is in two weeks

Quiz 4 covers Weeks 1–10, with its focus on Weeks 9 and 10, and is done without AI. Work through the Quiz 4 review first if you haven't yet.

Quiz 5 covers Weeks 11 and 12 and is also done without AI. Your instructor will share the details. Either way, the skill underneath is reading a dictionary loop or a comprehension and knowing what it produces before you run it. So this week, do the activities below with a pencil first, and use Thonny to check yourself afterward.

✅ Must do

These three are the core of the week. Do them first.

  1. The in-class activities. If you missed a class, ask a classmate or your instructor what you missed and work through it on your own.
  2. The reading: one of the options in "Read about it," below.
  3. PA4: SoDuckYou Parts A and B, plus test_count_patches and test_rule_breaks in test_soduckyou.py. Submit both files to Gradescope as soon as Part A works, and again when Part B does.

📚 Study menu (should do)

Class covered dictionary lookups and methods, looping over keys, values, and items, and comprehensions. Everything below is optional, but each item trains something PA4 or Quiz 5 needs. Pick what you need.

If you only have an hour

  1. Ten minutes. "Get it or crash?", below, on paper.
  2. Twenty minutes. "Group it by hand," on paper, then check it in Thonny.
  3. Thirty minutes. "Loop it, then comprehend it," both directions.

Read about it

Pick one option.

Python for Everybody: 10. Dictionaries and 11. Tuples

W3Schools: the reference-style skim

A few things you can skip for now

W3Schools' list of dictionary pages keeps going into Nested Dictionaries, which is next week's topic, so save it for then. Neither book covers set or dictionary comprehensions; they work just like list comprehensions with {} instead of [], and "Loop it, then comprehend it," below, has examples of both. If a page mentions lambda, you can skip that part. It isn't something this course covers.

Set or dictionary?

For each job, decide whether you'd store the data in a set, a dictionary, or a plain list, and write down what the keys and values would be for each dictionary.

  1. The usernames already taken on a website.
  2. Each student's score on a quiz.
  3. How many times each word appears in a book.
  4. The songs in a playlist, in order, with repeats allowed.
  5. The states you've visited.
  6. Each course and the students enrolled in it.
Check your answers

1 and 5 are sets: the only question is "is it in there?", and nothing goes with the answer. 2 and 3 are dictionaries, from student to score and from word to count. 4 is a list, because order and repeats matter, and a set keeps neither. 6 is a dictionary whose values are lists, from course to its students. That's nested data, next week's topic.

The rule to take away: if all you ask is whether something is there, use a set. If you need to know what goes with it, use a dictionary.

Get it or crash?

On paper, with d = {"a": 1, "b": 2}, write down what each line gives, or KeyError if it crashes. Then check them one at a time in the Shell.

Expression Your prediction
d["a"]
d["c"]
d.get("c")
d.get("c", 0)
"c" in d
1 in d
list(d.keys())
list(d.values())
list(d.items())
Check your answers

1, KeyError, None, 0, False, False, ['a', 'b'], [1, 2], and [('a', 1), ('b', 2)]. 1 in d is False because in checks the keys, never the values. items() hands you pairs, which is why for key, value in d.items(): can unpack each one into two variables.

The rules you should be able to state afterward:

  • d[key] crashes on a missing key, and d.get(key, default) returns the default instead.
  • in checks the keys, just as it checks the items of a set.
  • counts[x] = counts.get(x, 0) + 1 is the whole counting pattern in one line.

Group it by hand

A coffee cart logs every order as a (name, item) tuple. Trace this program on paper. Draw both dictionaries as two-column tables, and update them after each time through the loop, crossing out old values rather than erasing them.

orders = [("Ana", "coffee"), ("Ben", "tea"), ("Cal", "coffee"),
          ("Ana", "muffin"), ("Dee", "tea"), ("Ben", "coffee")]

counts = {}
by_person = {}
for name, item in orders:
    counts[item] = counts.get(item, 0) + 1
    if name not in by_person:
        by_person[name] = []
    by_person[name].append(item)

for item, n in sorted(counts.items()):
    print(item, n)
print(by_person)
Check your answers

It prints coffee 3, muffin 1, and tea 2, in that order, because sorted puts the items in alphabetical order by key. by_person ends up as {'Ana': ['coffee', 'muffin'], 'Ben': ['tea', 'coffee'], 'Cal': ['coffee'], 'Dee': ['tea']}.

The first dictionary summarizes (how many of each), and the second groups (what each person ordered). Those two shapes come up all the time, and next week's nested data is mostly the second one. To check your trace, step through it in Python Tutor and watch the tables fill.

Loop it, then comprehend it

Rewrite each loop as a single comprehension, on paper:

lengths = []
for word in words:
    lengths.append(len(word))

evens = []
for n in nums:
    if n % 2 == 0:
        evens.append(n)

initials = set()
for name in names:
    initials.add(name[0])

squares = {}
for n in range(1, 6):
    squares[n] = n * n

Then go the other way: write each of these as a loop, and predict what it gives.

{name: len(name) for name in ["Ana", "Benji", "Cal", "Dakota"] if len(name) > 3}
[c.upper() for c in "duck"]
{word[0]: word for word in ["apple", "avocado", "banana"]}
Check your answers

[len(word) for word in words], [n for n in nums if n % 2 == 0], {name[0] for name in names}, and {n: n * n for n in range(1, 6)}. The other three give {'Benji': 5, 'Dakota': 6}, ['D', 'U', 'C', 'K'], and {'a': 'avocado', 'b': 'banana'}. In the last one, "avocado" replaces "apple", because both have the key "a" and a dictionary keeps only the last value for a key.

When is a comprehension clearer? When the loop does one job: build a new collection, maybe keeping only some items. If the loop also counts, prints, or updates more than one thing, like the coffee cart above, keep the loop.

Try an AI tutor

AI is a good drill partner for dictionaries, as long as it hands you the questions and keeps the answers to itself.

"I'm a CS1 student learning dictionaries and comprehensions. Give me six short Python snippets, one at a time, that each loop over a dictionary or use a comprehension. Wait for my prediction of the output before you tell me if I'm right, and if I'm wrong, ask me a question that helps me see why instead of explaining it."

"Here is a loop I wrote. Don't rewrite it. Tell me whether it could be a comprehension, and if so, give me a hint about what goes before the for."

The thing to watch for this week is cleverness. AI loves collections.Counter, lambda, and comprehensions nested inside comprehensions. None of them is wrong, but PA4 rejects some of them, and a one-liner you can't trace by hand doesn't help you on Quiz 5. Ask for the plain version.

🔭 Explore more

Finished early, or just curious? None of these are required.

  • Read PY4E 11.6 The Most Common Words and use its trick to print the ten most common words in a book from Project Gutenberg.
  • Try dict(zip(["a", "b", "c"], [1, 2, 3])) in the Shell, and figure out what zip does.
  • Play a few levels of the puzzle SoDuckYou is based on, then design a 4 × 4 level of your own with exactly one solution. It's harder than it looks.

✍️ Reflection

Instructions

Download the Week 11 reflection template, type your answers into it, and submit the completed document.

The first three questions are quick; the short answers are the ones that matter. Question 4 is about how you tested your PA4 Parts A and B, so answer it after you submit. A few sentences each is plenty. Be specific and be honest.

Submit PA4 to Gradescope

If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.

1. What did you do this week? (Check all that apply.)

  • Worked through the in-class activities
  • Read the sections listed for one of the textbooks
  • Finished PA4 Parts A and B
  • Worked through the Quiz 4 review
  • Sorted the jobs in "Set or dictionary?"
  • Filled in the "Get it or crash?" table on paper
  • Traced "Group it by hand" on paper
  • Rewrote loops as comprehensions, and back
  • Asked an AI tutor to drill me
  • Tried something from "Explore more"
  • Something else (tell us in the short answers)

2. Roughly how much time did you spend on CS 149 outside of class this week?

  • Under 1 hour
  • 1–2 hours
  • 3–4 hours
  • 5–6 hours
  • 7+ hours

3. How comfortable are you reading a comprehension without running it?

  • Comfortable: I can say what it builds, and write it as a loop
  • Mostly: simple ones are fine, but an if at the end slows me down
  • Not yet: I still need to run it to see what it does
  • I haven't tried one yet

4. How did you test your program? Which asserts did you write for PA4 Parts A and B before you submitted, and what bug could each one have caught? Did you try a case with nothing in it, like no ducks or no sign-ups, or one where something shows up twice?

5. Give one dictionary operation or comprehension this week that did not do what you expected. It could be a KeyError you didn't see coming, an in that checked the keys when you meant the values, a comprehension that dropped items, or a count that came out one too high. Say what you expected, what happened, and the rule you were using that turned out to be wrong.

6. What is one thing you want gone over in class? Be as specific as you can: "why 1 in d is False when 1 is a value" is useful, and "dictionaries" is not. Class time gets spent on whatever shows up most often in these answers.

7. Did you use an AI tool this week, and did it build your understanding or replace it? The honest test: could you write PA4's Part A comprehension again on a blank page, then write it as a regular loop? If a video, article, or tutorial made something click, drop the link and one line on why it helped.

8. Paste your PA4 code for Parts A and B. If you rewrote a loop as a comprehension, or the other way around, say which one and why.