Skip to content
Dictionary Methods

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

NameDescription
keyThe key to look up.
defaultValue 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}")

Worth knowing

  • Direct indexing vs get(): settings["lineHeight"] raises KeyError, whereas settings.get("lineHeight", 1.5) falls back safely to 1.5.
  • Keys with None values: If a key exists with the value None, dict.get(key, default) returns None, not the default.

Related entries