Loading exercise...

Exercise: Check a Fruit Dictionary Key

Avatar image for PyPyPy

PyPyPy on Aug. 17, 2026

The solution’s selection is not clear to me. IMO when asked to do it safely and handling KeyError is explicitly stated as a (albeit, bonus) test, I’d assume I’m asked to use try/except clause instead of the ‘if’ clause. Alternatively, there is a clean one–liner solution in the default dictionary method .get() that returns its second parameter if key is missing.

What’s more, asking for forgiveness, not permission, is widely considered as more Pythonic, and even Python glossary (docs.python.org/3/glossary.html#term-EAFP) seems to advocate its usage against the look–before–you–leap approach (docs.python.org/3/glossary.html#term-LBYL).

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Aug. 20, 2026

@PyPyPy you’re right that .get() is the cleanest answer here, and in real code it’s what I’d reach for too:

def safe_lookup(data, key):
    return data.get(key, "NOT FOUND")

The reason the exercise doesn’t accept it is that it’s pinned to the lesson right before it, Checking the Existence of Dictionary Keys, which only covers the in keyword. The requirements say so directly (“Check whether the key exists in the dictionary using the in keyword before accessing it”), and there’s a test that parses your code looking for key in data, so both .get() and try/except fail it even though they give the right answers. At this point in Python Basics, try/except hasn’t been introduced yet, which is the real constraint behind that requirement.

On the bonus test, I think the wording misled you. “Does not raise a KeyError for missing keys” is checking that no KeyError escapes your function, not that you have to catch one. The in check satisfies it by never triggering the error in the first place.

Your EAFP point is worth taking seriously. I’d frame it a bit differently, since the glossary contrasts the two styles rather than crowning one. It calls EAFP “clean and fast” and describes LBYL as “characterized by the presence of many if statements.” But you’ve landed on something real, because the LBYL entry uses this exact pattern as its cautionary example:

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup.

That is the exercise’s solution, more or less verbatim. It isn’t a problem for a single-threaded beginner exercise, but it’s a good instinct to carry forward. I’ll pass your note about the requirement wording along to the rest of the team :)

Become a Member to join the conversation.