Dictionaries · Code Improvement

Shape — improve or specify L5 Synthesis Macro Structure ~5 min

Tighten this generated lookup

An AI produced the function below for: return the stock count for a product name, or 0 if the product is missing. The function works for the happy path but is unclear and brittle. Improve it. You may rewrite names, structure, and the missing-key case.

def get(d, x):
    # generated solution
    found = False
    answer = 0
    for k in d:
        if k == x:
            found = True
            answer = d[k]
    if found == True:
        return answer
    else:
        return 0
Why this activity was chosen
  • Bloom level: L5 Synthesis: Improve a working but weak generated solution.
  • Block Model level: Macro Structure (step 4 of 4): the purpose of the whole program: the problem it solves and the goal it serves.
  • Misconception targeted: shown after you answer, so it does not give the answer away.

Synthesis here means revising an existing artefact: names, structure, edge cases. Students start from AI-like output so the task is judgement plus rewriting, not blank-page authorship.

AI’s role here: AI may later comment on the student's revision. It must not hand back a fully rewritten program as the student's answer.