Lessons · Python · dict.get (missing keys)
Asking for a key that might not be there
Square brackets demand a key and crash if it is missing. get asks politely and hands back None instead.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Real data is full of holes. A user with no phone number, a config missing a setting, an API that omits a field. Code that assumes everything is present crashes on the first real customer.
How to think about it
Ask: can this key be missing, and if it is, what should happen? Choosing a sensible default is the actual decision. The syntax is the easy part.
Worked example
prices = {"apple": 40}One entry: the key apple, the value 40.prices["pear"]Crashes with KeyError. You demanded a key that is not there.
prices.get("pear")Hands back None. No crash, and you can check the result.prices.get("pear", 0)Hands back 0 instead of None, when a number suits you better.Your turn
Look up "fig" without crashing, defaulting to 0.
prices = {"apple": 40}
print(prices.("fig", 0))Solve one with the tests running
The trap
get never raises, which is usually what you want and occasionally hides a typo in a key name for hours.