← Back

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

  1. Check key membership first: in the dict, get returns the stored value and the default is irrelevant.
  2. Missing key with two arguments: the default is returned exactly as given.
  3. Missing key with one argument: the result is None.
  4. get never inserts: after the call, the dict is unchanged β€” unlike setdefault, which stores the default.

Common wrong fixes

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.

Solve it in the interactive editor β†’

πŸ’Ό 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