Home βΊ Problems βΊ Dictionary lookup with default
Dictionary lookup 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
What will this program print? Type the exact output (all 3 lines).
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:
user = {'name': 'Vikram', 'age': 20}
print(user['name'])
print(user.get('city', 'Jaipur'))
print(len(user))Understand the rule
Square-bracket lookups (`d[key]`) crash with `KeyError` the moment a key is absent, whereas `d.get(key, default)` provides a safe fallback expression. Output traps around `.get()` hinge on whether the key is actually missing versus present with a falsy value like `0` or `''`.
How to trace it
- Python hashes the lookup key and checks whether an equal key exists in the dictionary's hash table.
- If the key is present, `d.get(key, default)` returns the stored value β even when that stored value is `0`, `False`, `''`, or `None`.
- If the key is absent, `d.get(key, default)` returns the second argument (`default`), or `None` if no second argument was given.
- Crucially, `.get()` never inserts the default back into the dictionary (unlike `.setdefault()`).
Common wrong fixes
- Thinking `d.get('score', 10)` returns `10` when `'score': 0` is in the dictionary β `0` is a valid present key, so `0` is returned.
- Assuming `.get()` mutates the dictionary and increases `len(d)` on a missing lookup.
- Forgetting that `d.get('missing')` with one argument returns `None`, not an empty string or `0`.
Rule to remember
`d.get(k, fallback)` checks key membership (`k in d`), not truthiness, and leaves the dictionary unmodified.
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.