PCEP Practice Question: Functions, Tuples, Dictionaries and Exceptions
A support technician is running a Python script that parses a configuration file and stores key-value pairs in a dictionary called 'config'. The script then uses these values to set application parameters. The configuration file is optional, and some expected keys may be missing. Currently, the script crashes with a KeyError when accessing a missing key. The technician needs to modify the script to safely retrieve a value or return 'N/A' if a key is missing. The script must remain efficient and readable. Which modification best achieves this?
⚠ Common exam trap
The PCEP exam often tests the distinction between `dict.get()` and `dict.setdefault()`, trapping candidates who think `setdefault()` is a safe retrieval method without realizing it permanently modifies the dictionary by adding the missing key.
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 config.get(key, 'N/A') instead of direct key access
`dict.get(key, default)` is the idiomatic Python method for safely retrieving a value from a dictionary without raising a `KeyError`. It returns the default value `'N/A'` when the key is missing, which directly solves the crash while keeping the code concise and readable. This approach is more efficient than exception handling or explicit membership checks because it performs a single hash lookup.
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 config.get(key, 'N/A') instead of direct key access
Why this is correct
Using `config.get(key, 'N/A')` returns the supplied default when the key is absent, so no KeyError is raised. This satisfies the requirement to retrieve a value or fall back to 'N/A' for missing optional keys, while keeping the lookup a single, readable expression rather than a multi-line membership test.
- ✗
Wrap each access in a try-except block to catch KeyError and assign 'N/A'
Why it's wrong here
Wrapping every access in try-except adds repeated boilerplate and exception overhead, harming readability and efficiency across many keys. It is tempting because exception handling is the idiomatic Python pattern, and would be correct when the missing-key case is genuinely exceptional rather than an expected, routine condition.
- ✗
Use if key in config: value = config[key] else: value = 'N/A'
Why it's wrong here
The membership test followed by indexing performs two lookups per key and is verbose compared with dict.get, which retrieves the value or the default in a single call. It is tempting because explicit checks are clear to beginners, and would be correct where the fallback must run only on absence and no default-returning method exists.
- ✗
Use config.setdefault(key, 'N/A') before accessing
Why it's wrong here
setdefault inserts 'N/A' into config when the key is absent, permanently mutating the dictionary and returning the stored value on later lookups, which misrepresents missing keys. It is tempting because it avoids KeyError in one call, and would be correct when the intent is to populate defaults into the dictionary itself.
Go deeper
Related to this question
About these practice questions
This PCEP question is part of Courseiva's 482-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 →
Same concept, more angles
3 more ways this is tested on PCEP
These questions test the same concept from different angles. Work through them to make sure you can recognise it however the exam phrases it.
Variation 1. A dictionary student = {'name': 'John', 'age': 20}. To safely get the grade with a default of 'N/A', which code should be used?
easy- ✓ A.student.get('grade', 'N/A')
- B.student['grade']
- C.student.fetch('grade', 'N/A')
- D.student['grade'] or 'N/A'
Why A: The `get()` method of a dictionary safely retrieves the value for a given key, returning a default value (here `'N/A'`) if the key does not exist. This avoids raising a `KeyError` when the key `'grade'` is missing from the dictionary.
Variation 2. What is the result of the following expression? d = {'a': 1} d.get('b', 0)
easy- ✓ A.0
- B.None
- C.KeyError
- D.1
Why A: The `get()` method on a dictionary returns the value for the given key if it exists; otherwise, it returns the default value provided as the second argument. Since key `'b'` is not in dictionary `d`, the method returns `0` (the specified default). Option A is correct because `d.get('b', 0)` explicitly supplies a default of `0`.
Variation 3. What is the output of the code?
easy- A.AttributeError
- B.The program exits with no output
- C.None
- ✓ D.Key not found
Why D: The code uses a dictionary's `get()` method with a default value of 'Key not found'. When the key 'b' is not present in the dictionary `d`, `get()` returns the specified default instead of raising an exception. Therefore, the output is 'Key not found', making option D correct.
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.