Python foundations

Python dict.get(): Defaults and Missing Keys

Read an optional dictionary key with dict.get(). Distinguish a missing key from None, zero, False, and an empty string.

mapping.get(key, default) returns the stored value when a key exists. It returns default only when the key is missing and leaves the dictionary unchanged. If you omit the default, a missing key returns None. A stored zero, empty string, or None stays exactly as it was.

preferences = {"text_size": 0, "name": None}
assert preferences.get("text_size", 16) == 0
assert preferences.get("name", "Anonymous") is None
assert preferences.get("theme", "light") == "light"
assert "theme" not in preferences

text_size and name are present, so both keep their stored values. Only the lookup for theme uses a fallback. The final assertion shows that reading the fallback leaves the dictionary unchanged.

Treat optional and required fields differently

If a record is incomplete without an ID, record["id"] makes that expectation explicit. A missing key raises KeyError, giving you the opportunity to reject the malformed record at the input boundary. Using record.get("id", "") can silently introduce an empty ID into later processing. The resulting error may appear much farther from the source.

For an optional display setting, preferences.get("theme", "light") is an appropriate choice if light really is the documented fallback. Use a meaningful default that the rest of the program can handle. Avoid using a numeric zero to mean “not supplied” in a domain where zero is a valid reading.

Distinguish missing from null

When the fallback is None, you cannot tell from the returned value alone whether the key was absent or the caller set it to None. Use a membership check or use a unique sentinel object as the default.

missing = object()
record = {"note": None}
value = record.get("note", missing)

assert value is None
assert record.get("name", missing) is missing

A sentinel is a marker you can check by identity. Here, value is missing would tell you the field was absent, and value is None tells you the field was explicitly null. A membership test such as "note" in record is another way to distinguish those cases.

Why get(key) or default can lose a zero

record.get("count") or 10 substitutes 10 for every false value, including zero, an empty string, and False. That is useful only when you explicitly want to treat all such values as equivalent to missing. record.get("count", 10) preserves an existing zero. Decide what your default is supposed to represent before picking either expression.

Nested records deserve separate validation. profile.get("contact", {}).get("city") works for an absent contact mapping. It fails if the contact exists and is None, a string, or another value without a get method. Check how upstream data represents optional objects. A small validation function near the boundary is easier to debug than repeated chained defaults.

Know when a default is calculated

Python evaluates arguments before calling the method. data.get("label", build_default()) therefore runs build_default() even when the label already exists. If the fallback is expensive or has effects such as reading a file, do the lookup first and call the builder only for a missing result.

The same distinction matters if you want to store the default. get is a lookup. setdefault can create a missing entry, and defaultdict can create one on a bracket lookup. Confirm which behavior callers expect before choosing a method that mutates shared state.

Test the field states your program actually sees

Use separate test cases for a missing key, a populated key, and an explicitly null value when null is permitted. If the field is numeric, include zero. For text, decide whether an empty string is valid, absent for business purposes, or invalid. Test that policy separately from dictionary access. The dictionary can tell you which keys are present. Your application decides what those values mean.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org