CurriculumPython Dictionaries for KidsA missing key crashes — .get() doesn't have to
Python KeyError: Fixing It with dict.get()
dragon["mana"] crashes if mana was never set. dragon.get("mana", 0) doesn't.
A missing key crashes — .get() doesn't have to
One more thing about keys: asking for one that doesn't exist is a real crash.
dragon["mana"] raises a KeyError if "mana" was never set — Python won't guess a value for you.
dragon = {"name": "Ember"}
print(dragon["mana"]).get(key, default) asks SAFELY — if the key is missing, you get your own chosen default instead of a crash.
print(dragon.get("mana", 0))Output
0If the key DOES exist, .get() just returns the real value — the default only kicks in when it's actually missing.
Check your understanding
dragon = {"name": "Ember"}. What happens with print(dragon["mana"])?
dragon = {"name": "Ember"}
print(dragon["mana"])Why: A KeyError. dragon["mana"] with square brackets crashes on a missing key — .get() is the safe alternative when a key might not be there.
dragon = {"hp": 70}. What does dragon.get("hp", 0) return?
dragon = {"hp": 70}
print(dragon.get("hp", 0))Why: 70. The default in .get(key, default) is a FALLBACK — it only shows up when the key genuinely isn't there.
What you'll practice
dragon = {"name": "Ember", "hp": 40}. This code crashes with a KeyError trying to print dragon["mana"] — a key that was never set. Run it once to see the real error, then fix it with dragon.get("mana", 0) so it prints 0 instead of crashing.
More from this topic
A missing key crashes — .get() doesn't have to is one lesson inside Python Dictionaries for Kids — see the full lesson order and what the whole topic covers.
View the full topic →