Dictionaries: Values Found by Key · seed 1 · A4, ink-friendly. The answer key prints on its own page for grown-ups.

Find it by name, not by place

Computing · Programming · ages 16-17
Name ______________________   Date ____________
  1. Which of these is a correctly written dictionary?

    • ["apple": "red"]
    • ("apple" = "red")
    • {"apple": "red", "banana": "yellow"}
  2. With colors = {"apple": "red", "banana": "yellow"}, what does colors["banana"] give?

    • "yellow"
    • "banana"
    • "apple"
  3. Two keys in the same dictionary may be identical.

    Circle one:   True   False

  4. A program holds forecasts as a list of dicts and must total the "precip" field. What is the shape of the code?

    • set rainfall to 0, then add forecast["precip"] for each record
    • sort the list, then read the middle record
    • count the records, then divide by two
  5. In counts[word] = counts.get(word, 0) + 1, what happens on a word seen first?

    • the program raises an error
    • the word starts at 1
    • the word is skipped
  6. codes = {"US": 1, "IN": 91} maps countries to codes. The task is now to find the country for code 91. What is the fix?

    • build a reversed dict such as {1: "US", 91: "IN"}
    • add more countries to the same dict
    • loop over the list positions instead
  7. A coach stores race finishing order and asks what sits third. A friend proposes a dictionary keyed by runner name. Why is a list the better fit?

    • dictionaries cannot hold names
    • the question is about place, and a list answers by position
    • lists look up names faster
  8. A tally loop crashes on new words with counts[word] = counts[word] + 1. Which single change fixes it while keeping the loop?

    • sort the words before the loop
    • rename counts to word_list
    • use counts.get(word, 0) + 1 on the right side
LightMySky · lightmysky.comW1-mt_mofpj0n5AM-s1

Answer key

For grown-ups. Fold this page away before handing over the rest.

Find it by name, not by place W1-mt_mofpj0n5AM-s1

  1. {"apple": "red", "banana": "yellow"} · Pairs sit in curly braces with a colon between each key and value.
  2. "yellow" · Ask by key and the dictionary hands back its value, "yellow".
  3. False · Each key must point to exactly one value, so duplicates are not allowed.
  4. set rainfall to 0, then add forecast["precip"] for each record · Loop over the records and add the named field to a running total.
  5. the word starts at 1 · The helper supplies 0 for the missing key, and 0 + 1 starts the tally at 1.
  6. build a reversed dict such as {1: "US", 91: "IN"} · Lookup runs key to value only, so the keys must become the codes.
  7. the question is about place, and a list answers by position · By-name lookup cannot answer a by-place question, while a list is built for order.
  8. use counts.get(word, 0) + 1 on the right side · The crash is a missing key, and the helper supplies the starting 0.
Worksheet · LightMySky