Back
+10 XP
Concept

Accessing Keys & the Fatal `KeyError`

Asking for a key that does not exist in a dictionary immediately detonates your program with a fatal `KeyError`.

python
bot = {"name": "HAL"}
print(bot["name"])  # HAL
# print(bot["age"]) # KeyError: 'age'!

# 79. Accessing Keys & the Fatal `KeyError` Asking for a key that does not exist in a dictionary immediately detonates your program with a fatal `KeyError`: ```python bot = {"name": "HAL"} print(bot["name"]) # HAL # print(bot["age"]) # KeyError: 'age'! ``` Never blindly reach into a dictionary with square brackets unless you are 100% sure the key is present, or check it with `if key in d:` first.

Checkpoint

What happens if you run `d = {}; print(d['missing'])`?

Practice

Check if key `"level"` exists in `player = {"name": "Alex"}` using `in`, and print `"Found"` if True, or `"Missing"` if False.

Terminal
01
Tap code blocks below to assemble
Available Blocks