dict.get()
Python · Dictionaries
Theory
.get(key, default) returns the value for key if it exists, and otherwise returns default instead of raising an error. With employee = {'name': 'Asha', 'salary': 65000}, employee.get('bonus', 0) returns 0, while employee['bonus'] would raise KeyError: 'bonus'. If you leave out the default, get() returns None for missing keys. It never adds the key to the dict; the dict is unchanged after the call.
This makes get() ideal for optional fields, such as data from APIs where some records lack a key. It is also the classic counting idiom: counts[word] = counts.get(word, 0) + 1. Two subtleties: get() cannot tell a missing key apart from a key whose value is actually None, so use key in d when that distinction matters. And the default expression is evaluated every time, even when the key exists, so avoid expensive defaults. setdefault() is a cousin that also inserts the default into the dict.
Why we use it
Real data is incomplete: some customers have no phone number, some orders have no discount. get() lets your code handle missing keys gracefully with a sensible default instead of crashing.
When to use it
Use get() when a key is genuinely optional and a default makes sense. Use d[key] when the key must exist, so a missing key fails loudly. For counting or grouping many keys, collections.Counter or defaultdict is cleaner.
How it works
- Call employee.get('bonus', 0)
- Hash 'bonus' and look for it
- Is 'bonus' a key in the dict? Yes: Return its stored value. No: Return the default (0, or None if not given).
- The dict itself is not modified
- print shows 0
Syntax
dict.get(key, default)Example
employee = {'name': 'Asha', 'salary': 65000}
print(employee.get('bonus', 0))Key points
- Avoids a KeyError that employee['bonus'] would raise
- The default argument is optional; defaults to None
- Never adds the key; use setdefault() to insert it
- Counting idiom: counts[k] = counts.get(k, 0) + 1
- Cannot distinguish a missing key from a stored None; use in for that