access

dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None so this method never raises a KeyError.

d.get(key[, default])

Parameters

Parameter Purpose
key The key to look up in the dictionary
default Value returned when key is missing (defaults to None)

Examples

>>> d = {'a': 1, 'b': 2}
>>> d.get('a')
1

Returns the value for an existing key

>>> d = {'a': 1}
>>> d.get('missing')
>>> print(d.get('missing'))
None

Returns None (not KeyError) when key is absent

>>> d = {'a': 1}
>>> d.get('missing', 0)
0

Provide a fallback default to avoid None checks

>>> counts = {}
>>> counts['x'] = counts.get('x', 0) + 1
>>> counts
{'x': 1}

Common counter idiom (though Counter or setdefault are cleaner)

Gotcha

get returns None on missing key by default, not KeyError. The default argument is evaluated even when the key exists, so avoid expensive defaults; use setdefault or defaultdict for that.

Related methods

← All Python dict methods · String methods · Built-in functions