Question 226 of 498
PCEP Practice Question: Functions, Tuples, Dictionaries and Exceptions
A script uses a dictionary to store counts of words. The code `counts['apple'] += 1` raises a KeyError the first time because the key doesn't exist. Which approach best solves this?
⚠ Common exam trap
Python Institute often tests the misconception that `dict.get()` can be used directly in an increment expression, but candidates forget that `get` returns `None` for missing keys, leading to a TypeError rather than a KeyError.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Use `counts.setdefault('apple', 0)` then increment.
`setdefault('apple', 0)` inserts the key with a default value of 0 if it does not exist, then returns the value (0). After that, `counts['apple'] += 1` increments safely. This avoids a KeyError without requiring an explicit check or exception handling, making it the most concise and Pythonic approach for initializing missing dictionary keys.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
Use `counts.setdefault('apple', 0)` then increment.
Why this is correct
setdefault initializes if missing, then increment.
- ✗
Use `try-except` to catch KeyError and then set the key.
Why it's wrong here
Works but not the best practice.
- ✗
Use `counts['apple'] = counts.get('apple') + 1`
Why it's wrong here
get returns None if missing, causing TypeError.
- ✗
Use `if 'apple' in counts:` before incrementing.
Why it's wrong here
Does not handle the first occurrence.
About these practice questions
Courseiva creates original exam-style practice questions with explanations and wrong-answer analysis. It does not publish real exam questions, exam dumps, or protected exam content. Learn why practice questions differ from exam dumps →
Last reviewed: Jun 30, 2026
This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.
Question Discussion
Share a tip, memory trick, or ask about the reasoning behind this question. Do not post real exam questions, leaked content, braindumps, or copyrighted exam material. Comments are moderated and may be removed without notice.
Sign in to join the discussion.