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
- For each get call, decide membership first; that single fact selects value or default.
- In the counting idiom, run the first occurrence by hand: get returns 0, plus 1, stored as 1.
- Later occurrences read the stored count and increment it.
- Confirm the dict's final state: get alone never added keys; only the explicit assignment did.
Common wrong fixes
- Predicting a KeyError from get β that is the square-bracket behaviour, not get's.
- Thinking the default becomes permanent; without an assignment the dict stays as it was.
- Starting the count idiom at the default instead of default + 1 for the first occurrence.
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.
π¦ Learning path: Lists and Dictionaries
Problem 15 of 20 in this path. Work them in order β each one builds on the rule before it.
More dictionaries problems
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every dictionaries problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.