Python Dictionary get() With a Default Value

A Python dictionary get or default lookup uses dict.get(key, default): it returns the value if the key exists and your default if it doesn’t, without raising KeyError. Leave out the default and you get None:

price = prices.get("donut", 0.00)    # 0.0 if "donut" isn't a key

All of the examples below ran on Python 3.12.5, using a coffee shop menu priced in dollars.

We’ll compare get() with square brackets, tell None apart from a missing key, see how setdefault() differs, count with get(), dig into nested dicts, and avoid a default-argument trap.

Python dictionary get with a default value

d[key] raises KeyError for a missing key. get() returns None or the default you pass, and it never changes the dictionary:

prices = {"coffee": 3.75, "bagel": 2.50, "muffin": 3.25}

print(prices.get("bagel"))              # 2.5
print(prices.get("donut"))              # None: no error
print(prices.get("donut", 0.00))        # your own default
try:
    prices["donut"]
except KeyError as err:
    print("KeyError:", err)
print(prices)                           # get() never changes the dict

Output:

2.5
None
0.0
KeyError: 'donut'
{'coffee': 3.75, 'bagel': 2.5, 'muffin': 3.25}
Command Prompt output of Python dict.get returning a value, None, a default of 0.0, and a KeyError from square brackets
get() handled the missing donut quietly; square brackets raised KeyError.

I use brackets when a missing key would be a bug I want to hear about, and get() when it’s normal. More on the error itself in types of errors in Python.

How do you tell None from a missing key?

If a key can legitimately hold None, get() alone can’t tell you whether it’s missing. Use in, or pass a unique sentinel object as the default:

settings = {"theme": "dark", "coupon": None}     # coupon exists but is empty

print(settings.get("coupon"), settings.get("missing"))   # both look like None!
print("coupon" in settings, "missing" in settings)

MISSING = object()                                 # a unique marker no real value can equal
for key in ["coupon", "missing"]:
    value = settings.get(key, MISSING)
    print(key, "->", "not set" if value is MISSING else repr(value))

Output:

None None
True False
coupon -> None
missing -> not set
Command Prompt output of Python dict.get with a sentinel object telling a key set to None apart from a missing key
Both lookups returned None, but the sentinel shows coupon exists and missing doesn’t.

object() creates a value nothing else can be equal to, so comparing with is is completely safe. I keep one module-level MISSING for this.

get() vs setdefault() and counting with get()

They look alike, but setdefault() inserts the default into the dict, while get() only reads. get(key, 0) + 1 is the classic counting pattern:

from collections import Counter

cart = {"coffee": 2}
print(cart.get("bagel", 0), cart)                 # get: dict unchanged
print(cart.setdefault("bagel", 0), cart)          # setdefault: inserts the default

states = ["TX", "CA", "TX", "NY", "TX"]
counts = {}
for s in states:
    counts[s] = counts.get(s, 0) + 1              # the classic counting pattern
print(counts)
print(Counter(states))                            # same result in one call

Output:

0 {'coffee': 2}
0 {'coffee': 2, 'bagel': 0}
{'TX': 3, 'CA': 1, 'NY': 1}
Counter({'TX': 3, 'CA': 1, 'NY': 1})
Command Prompt output comparing Python dict.get and setdefault, then counting states with get and with Counter
setdefault added bagel to the cart; counting with get matches Counter.

For counting and grouping in bigger loops, defaultdict is often cleaner; see what is defaultdict in Python.

Safe lookups in nested dictionaries

JSON from an API is often nested, and any level might be missing. Chain get() calls with {} as the default, or write a tiny helper:

order = {"id": "A-2026-1128", "customer": {"name": "Emily", "address": {"city": "Austin", "state": "TX"}}}

print(order.get("customer", {}).get("address", {}).get("city"))
print(order.get("shipping", {}).get("carrier", "not assigned"))

def dig(d, *keys, default=None):
    for key in keys:
        if not isinstance(d, dict) or key not in d:
            return default
        d = d[key]
    return d

print(dig(order, "customer", "address", "state"))
print(dig(order, "customer", "phone", default="no phone"))

Output:

Austin
not assigned
TX
no phone
Command Prompt output of Python chained dict.get calls and a dig helper safely reading nested dictionary keys
Chained get() calls and the dig() helper both return a default instead of crashing.

Watch out: the default is always evaluated

Python evaluates arguments before calling get(), so an expensive default runs even when the key exists:

def load_default_price():
    print("  ...looking up the default price (slow call)")
    return 9.99

prices = {"coffee": 3.75}

print(prices.get("coffee", load_default_price()))   # runs even though coffee exists!

price = prices.get("coffee")
if price is None:
    price = load_default_price()                     # only runs when needed
print(price)

Output:

  ...looking up the default price (slow call)
3.75
3.75

If the default is slow, check for None first, as in the second half. Renaming keys is covered in rename a key in a dictionary.

Ways to read a dictionary key

CodeMissing key givesChanges dict?
d[key]KeyErrorNo
d.get(key)NoneNo
d.get(key, default)defaultNo
d.setdefault(key, default)defaultYes, inserts it
defaultdict[key]factory valueYes, inserts it

These dictionary guides are a good next step:

Frequently asked questions

How do I get a value from a dictionary with a default in Python?

Use d.get(key, default). It returns the default when the key is missing.

What does dict.get return if the key doesn’t exist?

None, unless you pass a different default as the second argument.

Does dict.get add the key to the dictionary?

No. get() only reads. setdefault() is the one that inserts.

Is get() slower than square brackets?

Very slightly, because it’s a method call. The difference rarely matters.

How do I safely get a nested value?

Chain calls like d.get("a", {}).get("b"), or write a small helper that walks the keys.

Where is dict.get documented?

See dict.get in the Python docs.