Reference

Reference · Dictionaries

dict.get()

dict.get(key, default=None) reads a value by key and returns a fallback instead of raising KeyError when the key is missing — the safe way to read a dictionary.

XCODXReference · Updated

Definition

dict.get() looks up a key and returns its value, but unlike square-bracket access it never raises. When the key is present it returns the associated value; when the key is absent it returns a fallback — None by default, or whatever you pass as the second argument. It is the method to reach for whenever a key *might* be missing, because it turns a potential crash into a predictable default.

The contrast with d[key] is the whole point. Bracket access raises KeyError on a missing key, which is correct when the key is guaranteed and you *want* to fail loudly, but a liability when the key is optional. get trades that exception for a value you choose, so lookups on user input, parsed data, and sparse records stay total instead of throwing halfway through.

get is a read-only operation: it inspects the dictionary and returns, but it never inserts the key or changes anything. That distinguishes it from setdefault(), which returns a value the same way but *also writes* the key into the dict when it was missing. If you only want to read, get is the honest, side-effect-free choice.

Syntax

value = d.get(key)            # missing -> None
value = d.get(key, default)   # missing -> default

# key:     the key to look up
# default: what to return when the key is absent (defaults to None)

Parameters

ParameterRequiredDescription
keyYesThe key to look up. Any hashable value. If it is present in the dictionary, its value is returned.
defaultNoThe value returned when key is absent. Defaults to None. It is only returned, never inserted into the dictionary.

get is an instance method, called on the dictionary itself as d.get(...). The default argument is evaluated whether or not it is needed, so if computing it is expensive, prefer an explicit membership test with in.

Return value

The value stored under key if the key exists; otherwise default (or None when no default was given). The dictionary itself is never modified — no key is added, no value is changed.

  • Key present -> the stored value, exactly as-is (a reference, for lists and dicts).
  • Key absent, default given -> the default value.
  • Key absent, no default -> None.
  • A key whose value is None returns None, indistinguishable from a missing key — use in if you must tell them apart.

Examples

Read a value that might be missing

book = {"title": "Dune", "pages": 412}

print(book.get("title"))    # Dune
print(book.get("author"))   # None  (missing, no crash)

Supply a fallback default

settings = {"theme": "dark"}

print(settings.get("theme", "light"))   # dark   (present)
print(settings.get("font", "sans"))     # sans   (default used)

get never modifies the dictionary

counts = {"a": 1}

counts.get("b", 0)
print(counts)   # {'a': 1}  - 'b' was not added by get

Count occurrences with get(k, 0) + 1

words = ["pear", "apple", "pear", "fig", "apple", "pear"]

counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1   # start at 0 the first time a word is seen

print(counts)   # {'pear': 3, 'apple': 2, 'fig': 1}

get vs d[key] on a missing key

prices = {"pen": 3}

print(prices.get("book"))        # None   - get returns the fallback
try:
    print(prices["book"])        # bracket access raises instead
except KeyError as err:
    print("KeyError:", err)      # KeyError: 'book'

Chain get for a safe nested lookup

config = {"db": {"host": "localhost"}}

host = config.get("db", {}).get("host", "?")
port = config.get("db", {}).get("port", 5432)
print(host)   # localhost
print(port)   # 5432  - default fills in the missing nested key

The default argument is always evaluated

def build_default():
    print("building default...")   # runs even when the key is present
    return []

d = {"items": [1, 2, 3]}
print(d.get("items", build_default()))   # building default... then [1, 2, 3]

Browser & runtime support

get vs bracket access vs setdefault

The three ways to read a dictionary differ only in what they do when the key is missing. d[key] raises KeyError — use it when the key is guaranteed and a missing one is a genuine bug you want surfaced. d.get(key, default) returns a fallback and leaves the dict untouched — use it when absence is normal. d.setdefault(key, default) returns the same fallback but *also stores* it under the key, which is handy when building a dictionary incrementally but a surprising side effect if you only meant to read.

One subtle point is worth spelling out. Because get returns your default for a missing key *and* returns the stored value for a present key, it cannot distinguish a key that is absent from a key whose value happens to be None. Both come back as None. When that distinction matters — an optional field that may legitimately be set to None — test membership explicitly with if key in d before reading, rather than relying on the return value of get to tell you whether the key existed.

Availability

dict.get() is a core dictionary method available in every version of Python 2 and 3 — nothing to import, nothing to enable. It is one of the oldest and most stable parts of the language, so any code you write against it runs unchanged across every interpreter you are likely to meet.

Frequently asked questions

What does dict.get() return when the key is missing?
It returns the default you pass as the second argument, or None if you did not pass one. It never raises KeyError.
How is dict.get() different from d[key]?
d[key] raises KeyError when the key is missing; d.get(key) returns None (or your default) instead. Use brackets when the key is guaranteed, get when it may be absent.
Does dict.get() add the key to the dictionary?
No. get only reads — it never inserts the key or changes a value. If you want the default written into the dict, use setdefault() instead.