Skip to content
Tutorials Center
My learning

Topics

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.

Python
user = {"name": "Ada"}
print(user.get("name"))       # Ada
print(user.get("email", "-")) # -

Try it

Python Safe lookups

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.

Python Counting and pitfalls

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

Python
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. Use dict.setdefault() or collections.defaultdict to store it.
  • A stored None looks like a missing key. d.get("k") returns None in both cases. Test "k" in d when the difference matters.
  • Avoid get(key) or default for 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()) calls expensive() every time, even when the key exists. Use an if key in d check or try/except KeyError for costly defaults.
  • Positional-only. Both parameters are positional-only, so get(key=1) raises TypeError.
  • 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, and getattr() is the attribute equivalent.