← Back

Home β€Ί Problems β€Ί Deleting a key that doesn't exist

Deleting a key that doesn't exist

πŸ› Fix the bug 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 a fix-the-bug problem: a short program is given in its broken state, and the task is to repair the code so it produces the required output. The interactive editor runs your fixed version in the browser and checks it for you β€” no setup, no local interpreter.

Difficulty: easy β€” the fix or the trick is normally a single line, and a careful read should be enough.

The challenge

This should remove a setting, but crashes because it's already gone. Fix it.

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: 'brightness'. 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, broken and ready to repair:

settings = {"volume": 50}
del settings["brightness"]
print(settings)

Understand the rule

del data['key'] raises KeyError when the key is absent β€” deletion is a lookup first. This bites when the same key can be removed twice (a retry, a double-click, a loop) or when cleanup code runs on dicts that never had the key. Python offers pop() with a default precisely for 'remove it if present' semantics.

How to trace it

  1. Confirm the crash is on a del statement, not a read; the traceback points at it directly.
  2. Ask whether the key is guaranteed to exist at this point β€” if yes, the real bug is whoever removed it early.
  3. For optional removal, replace del with data.pop('key', None), which never raises.
  4. If the code loops while deleting, check whether the same key can be visited twice.

Common wrong fixes

Rule to remember

del requires the key to exist; dict.pop(key, default) is the idiomatic 'remove if present'. Choose del only when a missing key genuinely means another bug.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

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

← Previous problemNext in path: Wrong syntax for adding a new key β†’

More dictionaries problems

Keep going