← Back

Home β€Ί Problems β€Ί Nested dictionary access

Nested dictionary access

🧠 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 error it raises

Run the broken snippet and Python stops with this exact error: KeyError: 'address'. Match it to the Python errors guide, then repair the line that produced it β€” knowing the message is half the fix.

The snippet

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

user = {
    "name": "Kabir",
    "address": {"city": "Delhi", "pincode": 110001}
}
print(user["address"]["city"])
print(user.get("phone", "N/A"))

Understand the rule

data['user']['address']['city'] is a chain of separate lookups, evaluated left to right, and it fails at the FIRST missing link β€” the KeyError names that key, not the whole path. Mixing in get() changes the failure mode: data.get('user') returns None when absent, and the next ['address'] then raises TypeError: 'NoneType' object is not subscriptable instead of a KeyError.

How to trace it

  1. Split the chain mentally: temp1 = data['user'], temp2 = temp1['address'], and so on.
  2. At each step confirm the current object is a dict and contains the next key.
  3. Identify the first failing step; its exception (KeyError with the key's name) is the whole output if uncaught.
  4. If get() appears mid-chain, track None: the error becomes a TypeError one step later than the real problem.

Common wrong fixes

Rule to remember

Nested access fails at the first missing key, and the exception names it. Chained get() trades KeyError for a later NoneType TypeError β€” know which failure you are predicting.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

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

← Dictionary keys must be unique🏁 Path complete β€” review it β†’

More dictionaries problems

Keep going