get()
Look up a value safely without raising a KeyError if missing.
dict.get(key, default=None)
dict.get() returns the value for key if it exists in the dictionary; otherwise, it returns the specified default value.
This is the safest and cleanest way to query optional configuration or dictionary data.
Parameters
- key
- The key to look up.
- default
- Value returned if the key is not found. Defaults to
None.
Returns
The value associated with the key, or
default (or None) if absent.Try it
Run it and change it
settings = {"fontSize": 14, "darkMode": True}
font = settings.get("fontSize", 12)
line_height = settings.get("lineHeight", 1.5)
print(f"Font: {font}, Line Height: {line_height}") Output
Press Run to see what it prints.Worth knowing
- Direct indexing vs get():
settings["lineHeight"]raisesKeyError, whereassettings.get("lineHeight", 1.5)falls back safely to1.5. - Keys with None values: If a key exists with the value
None,dict.get(key, default)returnsNone, not the default.