Python Reference ยท Dictionaries and Sets
Python dict.get() method
Reference for Python dict.get(): read a value without a KeyError, supply a default, how it differs from d[key] and setdefault(), and the None-value pitfall.
The dict.get() method looks up a key and returns its value. If the key is missing it returns a default instead of raising a KeyError. The default is None unless you give another one.
Use get() when a missing key is a normal situation, such as optional settings or counting items for the first time. When a missing key means a bug, plain d[key] is better, because the KeyError tells you immediately.
user = {"name": "Ada"} print(user.get("name")) # Ada print(user.get("email", "-")) # -
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.get(key, default=None, /)
| Name | Description |
|---|---|
key |
The key to look up. It must be hashable. |
default |
Optional. What to return when key is not present. Defaults to None. |
Return value: the value stored for key, or default when the key is missing.
Raises: TypeError if key is not hashable. It never raises KeyError.
Usage notes
- The dictionary is not changed.
get()never inserts the default. Usedict.setdefault()orcollections.defaultdictto store it. - A stored
Nonelooks like a missing key.d.get("k")returnsNonein both cases. Test"k" in dwhen the difference matters. - Avoid
get(key) or defaultfor values that may be falsy (0,"",[]). It replaces them with the default. Pass the default as the second argument instead. - The default is evaluated eagerly.
d.get(k, expensive())callsexpensive()every time, even when the key exists. Use anif key in dcheck ortry/except KeyErrorfor costly defaults. - Positional-only. Both parameters are positional-only, so
get(key=1)raisesTypeError. - Mutable defaults are fine for reading, but returning a shared
[]and then appending to it will not update the dict. - Nested lookups chain safely only if every level is a dict:
d.get("a", {}).get("b"). - Same name elsewhere.
os.environ.get()works the same way, andgetattr()is the attribute equivalent.