PCEP Computer Programming and Python Fundamentals Practice Question
You are a developer on a team that maintains a legacy Python 2 codebase being migrated to Python 3. One function reads a file in text mode and counts word frequencies. In Python 2, the code used the dict.iteritems() method to iterate over the dictionary. After migration, the code raises AttributeError: 'dict' object has no attribute 'iteritems'. You need to update the code to work in Python 3 while minimizing changes. Which action should you take?
⚠ Common exam trap
The PCEP exam often tests the misconception that Python 3 requires an external library or a different method name to achieve the same iteration behavior, when in fact `items()` alone is the correct and minimal replacement for `iteritems()`.
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
✓
Replace iteritems() with items().
In Python 3, the `dict.iteritems()` method was removed because `dict.items()` now returns a view object that provides lazy iteration, similar to what `iteritems()` did in Python 2. Replacing `iteritems()` with `items()` is the minimal change that preserves the iteration behavior and works correctly in Python 3.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Replace iteritems() with viewitems().
Why it's wrong here
viewitems() does not exist in Python 3.
- ✗
Replace iteritems() with iteritems() from the six compatibility library.
Why it's wrong here
Adding a third-party library for a simple fix is overkill.
- ✓
Replace iteritems() with items().
Why this is correct
items() in Python 3 returns a view that works similarly.
- ✗
Convert the dictionary to a list of tuples and iterate over the list.
Why it's wrong here
Unnecessary conversion; items() is sufficient.
Go deeper
Related to this question
About these practice questions
One of 498 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
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.