Courseiva
Functions, Tuples, Dictionaries and ExceptionsmediumMultiple ChoiceObjective-mapped

PCEP Practice Question: Functions, Tuples, Dictionaries and Exceptions

A script counts occurrences of words in a text file. The current code uses: if word in count_dict: count_dict[word] += 1 else: count_dict[word] = 1. Which alternative is more concise and Pythonic?

⚠ Common exam trap

The PCEP exam often tests the distinction between `dict.get()` and direct indexing, trapping candidates who forget that direct access (`dict[key]`) raises `KeyError` for missing keys, while `get()` safely returns a default.

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

count_dict[word] = count_dict.get(word, 0) + 1

`dict.get(word, 0)` returns the current count for `word` (or 0 if missing), then adds 1 and assigns back. This replaces the explicit `if/else` with a single line, making the code more concise and Pythonic while preserving the same logic.

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 collections.Counter

    Why it's wrong here

    Counter is a specialized tool, but the question asks for a modification using built-in constructs; also Counter may not be imported.

  • count_dict[word] = count_dict[word] + 1

    Why it's wrong here

    This will raise KeyError if the word is not already in the dictionary.

  • count_dict.setdefault(word, 0); count_dict[word] += 1

    Why it's wrong here

    This works but is two lines and less efficient than the get() approach.

  • count_dict[word] = count_dict.get(word, 0) + 1

    Why this is correct

    The get() method returns the current count or 0 if missing, allowing a one-liner update.

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 →

How Courseiva writes practice questions · Editorial policy

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.