PCEP Control Flow, Loops, Lists and Logic Practice Question
A data analyst is processing a large dataset of customer transactions. The dataset is stored as a list of dictionaries, each with keys 'amount' and 'date'. The analyst needs to compute the total revenue for 2024. They write:
total = 0
for t in transactions:
if t['date'].year == 2024:total += t['amount']
They then run it and get a KeyError: 'date'. After inspection, they notice that some records have a 'Date' key (capital D) instead. The analyst wants to fix this without modifying the data. Which approach will correctly sum amounts regardless of key case?
⚠ Common exam trap
Python Institute often tests the distinction between direct key access (`dict[key]`) which raises KeyError, and the safer `dict.get()` method, and the trap here is that candidates may think a try-except block is the only way to handle missing keys, overlooking the more Pythonic and concise `.get()` with a fallback.
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
✓
Change the if condition to: if t.get('date', t.get('Date')).year == 2024
`dict.get(key, default)` safely attempts to retrieve the value for 'date', and if that key is missing, it falls back to retrieving the value for 'Date'. This handles the case inconsistency without modifying the original data and avoids a KeyError. The `.year` attribute is then accessed on the returned date object.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✓
Change the if condition to: if t.get('date', t.get('Date')).year == 2024
Why this is correct
Correct: get with fallback handles both key casings.
- ✗
Use a try-except block to catch KeyError and use alternative key
Why it's wrong here
Works but is less efficient and less Pythonic than get().
- ✗
Convert all keys to lowercase before processing
Why it's wrong here
Modifies original data, which may not be allowed.
- ✗
Use a list comprehension with conditional chaining
Why it's wrong here
Not clear how to handle missing keys without get.
Go deeper
Related to this question
About these practice questions
This PCEP question is part of Courseiva's 498-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. 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.