I started learning Python this week for

· Answered by the Doramagic.ai AI assistant · Learn one thing

Question

I started learning Python this week for data automation at work.
Today my small script crashed with a 'KeyError: theme' when I ran config['theme'] on a dictionary where that key hadn't been set yet.
A colleague told me I should use .get('theme', 'light') instead of bracket notation ['theme'].
Can you give me:

  1. A 10-minute micro-goal explaining the core difference: bracket access dict[key] requires the key to exist or raises KeyError, while .get(key, default) safely returns a fallback value.
  2. A minimal, 4-line runnable demo dictionary showing both behaviors in action.
  3. A small micro-task for me to write and run tonight to test my understanding?

Answer

Tonight's one move: run a tiny dict with both access styles, see the difference, and write your own.

Goal (10 min): un a 4-line Python snippet that uses `dict.get(key, default)` on a missing key (returns the fallback) and `dict[key]` on the same missing key (raises `KeyError`). You can paste the output and tell me which line crashed.

Demo — copy, paste, run:

```python
config = {"lang": "en"}
print(config.get("theme", "light")) # light (safe fallback)
try: print(config["theme"]) # raises KeyError
except KeyError: print("caught") # caught
```

You should see:
```
light
caught
```

What just happened:

  • Line 2 — `.get("theme", "light")` didn't find `"theme"`, so it handed back the fallback `"light"`. The script kept going.
  • Lines 3–4 — `config["theme"]` *did* raise `KeyError`, but `try/except` caught it. Without the `try`, the whole script would stop on that line. (No need to learn `try/except` tonight — just notice that `[]` *demands* the key, `.get()` *suggests* it.)

The rule to remember:

formif key missing
`d[key]`crashes with `KeyError`
`d.get(key, default)`returns `default`

Your turn — micro-task:

  1. Make a dict with at least one real key, e.g. `user = {"name": "alex", "role": "admin"}`.
  2. Add one line using `user.get("theme", "dark")` and print the result.
  3. Add one line using `user["theme"]` (no try/except) and run it.
  4. Paste the output (or the traceback) back to me, and tell me in one sentence: *which form would you reach for first when reading a config that may be missing keys, and why?*

That's the whole task. Stop there and tell me what you saw.