Organizing Data

Processing and Building Dictionaries


Learning Objectives

  • You can iterate over dictionary keys and key-value pairs.
  • You can use a dictionary to accumulate a separate count for each category.
  • You can build a result dictionary without changing its input.
  • You can distinguish replacing existing values from changing the keys during iteration.

A dictionary may represent one record, such as a book. It can also represent a lookup table: a connection from each category to its count, each product to its stock, or each identifier to some information.

The loop patterns are familiar. The new question is which keys and values the dictionary should contain.

Direct Iteration Produces Keys

stock = {"notebook": 4, "pencil": 12, "eraser": 3}
for product in stock:
print(f"{product}: {stock[product]}")

Each iteration binds product to one key. The bracket lookup retrieves the value for that key.

For this dictionary, the output is:

notebook: 4
pencil: 12
eraser: 3

Dictionaries preserve insertion order. That does not make them lists: the access operation still uses a key, and the keys are not automatically sorted. We will ask for sorted output explicitly later in the part.

The same structure can calculate a total:

total = 0
for product in stock:
total = total + stock[product]
assert total == 19

There is no new accumulation algorithm here. Instead of adding a list item directly, the loop retrieves the value associated with its current key.

Retrieve a Key and Its Value Together

The .items() method lets a loop receive a key and its value together:

for product, quantity in stock.items():
print(f"{product}: {quantity}")

The two names are assigned from one pair on each iteration. On the first iteration, product is "notebook" and quantity is 4. This is called unpacking. Each item produced by .items() is a two-item tuple, a fixed sequence containing the key and value. You do not need a separate tuple-processing technique to use this loop.

Choose the version that makes the operation clearer. A key-only loop is useful when the key drives several lookups. An items loop is convenient when both the key and value are needed together.

Tracing makes the difference between a key-only loop and an items loop visible. Choose deliberately between those forms when you process another dictionary.

Prepare a stock list

0 / 15 points

Write low_stock(stock, minimum). The dictionary maps product names to nonnegative integer quantities; the minimum is a nonnegative integer. Return a new list of names whose quantity is strictly less than the minimum, in dictionary iteration order. Return [] when none qualify. Do not print or change stock.

For {"pen": 4, "paper": 12, "eraser": 3} and minimum 4, return ["eraser"].

A Separate Counter for Each Key

Part 2 used one counter to count selected characters. What if we need a count for every word?

No files opened Select a file to edit

Each key has its own counter. Before using the stepper, predict the dictionary after each of the first three words: "red", "blue", and "red" again. Does the initialization line run on all three iterations?

The stepper uses just those three words. Check your predictions by following which lines execute and which dictionary entry changes.

Code

Step 1 of 15

1 / 15
Formatting...

State

main

No variables

Objects

No objects yet

Output

No output yet

The repeated "red" must keep its earlier count before adding one. Initialization belongs inside the missing-key condition; incrementing belongs after it. You could shorten the update using .get(word, 0), but use the explicit version until you can explain these two responsibilities.

Arrange a category count

0 / 4 points

Arrange the blocks into a program that counts the supplied labels and then prints 2. The loop block moves with its indented body.

The arranged program supplies the control-flow skeleton for per-category counting. The next task asks you to decide what should count as a category and which input values belong outside the result.

Count letter use

0 / 15 points

Write letter_counts(text). The text contains lowercase English letters and spaces only. Return a dictionary counting each letter that occurs. Ignore spaces and omit letters that do not occur. Empty text and spaces-only text return {}. Do not print.

For "a cab", return {"a": 2, "c": 1, "b": 1}. Dictionary entry order is not graded.

Updating Values While Iterating

Replacing values for existing keys is different from adding or deleting keys:

stock = {"notebook": 4, "pencil": 12}
for product in stock:
stock[product] = stock[product] + 1
assert stock == {"notebook": 5, "pencil": 13}

The loop still visits the same keys. By contrast, changing the set of keys while iterating over that dictionary can invalidate the iteration. When selecting entries, build another dictionary instead:

def available_stock(stock):
available = {}
for product, quantity in stock.items():
if quantity > 0:
available[product] = quantity
return available

For the numeric values used here, the result can be updated independently without changing the original dictionary’s entries. Later chapters examine what changes when values are themselves mutable collections.

Review the counter and selection patterns before writing another dictionary function:

Selection and transformation can both build a result dictionary. The difference is whether an input entry determines membership in the result or the value stored there.

Prepare restocked quantities

0 / 15 points

Write restocked(stock, extra). Stock maps names to nonnegative integer quantities, and extra is a nonnegative integer. Return a new dictionary with the same keys and with extra added to every quantity. Keep the original dictionary unchanged. Empty stock returns {}. Do not print.

For {"pen": 0, "paper": 8} and 3, return {"pen": 3, "paper": 11}. The returned dictionary must remain independent even when extra is zero.

Check Your Understanding

  1. What does a direct for loop over a dictionary produce?
  2. What do the two names in an .items() loop receive?
  3. Why does a per-key counter initialize only when a key is new?
  4. Why does preserving insertion order not mean the keys are sorted?
  5. Why is building a new dictionary a useful way to select entries?

LEIA activity: dictionaries

In this activity, you will practise counting with dictionaries and selecting entries for a new dictionary by completing a programming task with an AI simulated client on the LEIA platform. You will be randomly assigned to a text-based or voice-based version.

This is part of a research study. The study explores how these ways of interacting support programming and learning. You can read more from the participant information sheet and the privacy notice. Research participation is voluntary; your research consent choices do not affect the course points available for these exercises.

Do not enter personal or sensitive information in the LEIA platform. This includes names, personal email addresses, student numbers, and any other identifying details in your messages, speech, code, or comments.

The voice-based version requires a microphone and speakers or headphones. If you have technical problems or cannot use the voice-based version, contact the course staff for access to the text-based version.

LEIA Conversation Viewer Link

0 / 5 points

Follow these steps to complete the LEIA activity and submit your Conversation Viewer Link:

  1. Open the Dictionary activity. In the window that opens, click Open link.
  2. The next page has an automatically generated test email address ending in @test.com. Do not modify this email address or the Replication code, and do not enter your own email address. Click Start session.
  3. The activity begins with a research consent question. Choose either Yes, I consent or No, I do not consent. Either choice lets you complete the activity and receive the same course points.
  4. Follow the activity instructions and finish the activity. At the end, copy the Conversation Viewer Link provided by LEIA.
  5. Paste the complete link into the answer field below, without adding any other text, to receive 5 course points.
  6. Once your link is accepted, the survey below will unlock automatically.

Once you have completed the activity and submitted your Conversation Viewer Link, please complete the survey below.

Survey about the LEIA activity

0 / 5 points

The first question asks for your consent to use these survey responses for research. Leaving the consent question unanswered is treated as not consenting.

All questions are optional. You may select “No, I do not consent”, skip any questions, or leave the entire form blank. Submit this survey step to receive 5 course points, regardless of your consent choice or the content of your answers. Regardless of your consent choice, please try to answer the questions as honestly as possible. Your consent choice and the content of your answers do not affect these points.