Home βΊ Problems βΊ Dictionary get with a default
Dictionary get with a default
π§ Predict the output Topic: dictionaries Difficulty: medium 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: medium β expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.
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:
user = {"name": "Aisha", "age": 22}
print(user.get("name"))
print(user.get("email", "Not provided"))Understand the rule
d.get(key, default) is the crash-free lookup: it returns the stored value when the key exists and the default when it does not β never a KeyError. The prediction traps are precise: get with one argument returns None (which prints as None), the default is ignored when the key exists, and a stored value of None is indistinguishable from a missing key through get alone.
How to trace it
- Check key membership first: in the dict, get returns the stored value and the default is irrelevant.
- Missing key with two arguments: the default is returned exactly as given.
- Missing key with one argument: the result is None.
- get never inserts: after the call, the dict is unchanged β unlike setdefault, which stores the default.
Common wrong fixes
- Expecting the default to override an existing value.
- Believing get(key) raises on a missing key like square brackets do.
- Confusing get with setdefault: only the latter writes to the dictionary.
Rule to remember
get returns value-if-present, else default (None if omitted), and never mutates the dict. If the dict must gain the key, that is setdefault β a different tool.
πΌ Learning path: Interview Practice
Problem 9 of 16 in this path. Work them in order β each one builds on the rule before it.
β Dictionary keys must be uniqueNext in path: Sorting doesn't return a new list β
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.