← Back

Home β€Ί Problems β€Ί Dictionary get with default

Dictionary get with default

🧠 Predict the output Topic: dictionaries Difficulty: easy Free

What this problem practises

Dictionaries fail loudly on a missing key with KeyError, quietly through get(), and in genuinely surprising ways when you modify a dict while iterating it or rely on a duplicate key silently replacing the earlier entry.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

scores = {"alice": 90, "bob": 85}
print(scores.get("alice"))
print(scores.get("charlie"))
print(scores.get("charlie", 0))

Understand the rule

This easier companion drills the core get() contract with simple data: d.get('missing', 0) yields 0 without touching the dict, while d.get('present', 0) ignores the fallback entirely. It also covers the counting idiom built on it β€” counts[ch] = counts.get(ch, 0) + 1 β€” where the default seeds the very first occurrence.

How to trace it

  1. For each get call, decide membership first; that single fact selects value or default.
  2. In the counting idiom, run the first occurrence by hand: get returns 0, plus 1, stored as 1.
  3. Later occurrences read the stored count and increment it.
  4. Confirm the dict's final state: get alone never added keys; only the explicit assignment did.

Common wrong fixes

Rule to remember

get(key, default) is a read-only lookup with a fallback. Paired with assignment it builds counters safely β€” the default handles exactly the first sighting of each key.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

Problem 15 of 20 in this path. Work them in order β€” each one builds on the rule before it.

← Previous problemNext in path: Next problem β†’

More dictionaries problems

Keep going