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
dict.setdefault
If key is in the dictionary, returns its value. If not, inserts key with a value of default (None if omitted) and returns default.
key in dict
Membership test invoking __contains__ — returns True if key exists in the dictionary. The check is against keys only (never values) and runs in O(1) average time.
dict.pop
Removes the specified key and returns its value. If the key is missing, returns default if provided; otherwise raises KeyError.
← All Python dict methods · String methods · Built-in functions