Dictionary method

dict.get()

Returns the value for a key, or a default value (None unless you give one) when the key is missing, instead of raising KeyError.

BeginnerEvery example below runs in your browser. Change the code and press Run.

dict.get(key, default=None, /)

d.get(key) looks up a key like d[key] does, with one difference: if the key is not there, you get None (or the default you choose) instead of a KeyError that stops your program.

Use it whenever a key may or may not be present: optional settings, data from a form or a file, or counting things with counts.get(word, 0) + 1.

get() only reads. It never adds the missing key to the dictionary. If you want the default stored as well, use dict.setdefault().

Parameters

ParameterWhat it is
key
required
The key to look up.
default
optional, default None
What to return when the key is missing. It is not stored in the dictionary. Give it by position, d.get(key, 0): default=0 raises TypeError.

Return value

The value for key if it exists, otherwise default.

Examples

1Square brackets vs get()

Pythoneditable
prices = {"coffee": 2.5, "tea": 2.0}
print(prices["coffee"])
print(prices.get("tea"))
print(prices.get("juice"))
Output
2.5
2.0
None

prices["juice"] would raise a KeyError; get() quietly returns None.

2Give your own default

Pythoneditable
settings = {"theme": "dark"}
theme = settings.get("theme", "light")
lang = settings.get("language", "en")
print(theme, lang)
print(settings)
Output
dark en
{'theme': 'dark'}

The default is only returned; the dictionary does not change.

3Count words

Pythoneditable
text = "to be or not to be"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Output
{'to': 2, 'be': 2, 'or': 1, 'not': 1}

4Read optional fields from a record

Pythoneditable
users = [
    {"name": "Lena", "city": "Vienna"},
    {"name": "Omar"},
]
for u in users:
    print(u["name"], "-", u.get("city", "city unknown"))
Output
Lena - Vienna
Omar - city unknown

Common mistakes

Using square brackets for a key that may be missing

d[key] raises KeyError when the key is absent. Use get() when missing keys are normal.

Pythoneditable
stock = {"pens": 4}
try:
    print(stock["ink"])
except KeyError:
    print("KeyError: no 'ink' key")
print(stock.get("ink", 0))
Output
KeyError: no 'ink' key
0

Testing get() when the value can be falsy

if d.get(key): is also false when the key exists with the value 0, "" or False. To ask "is the key there?", use in.

Pythoneditable
scores = {"Ana": 0}
if not scores.get("Ana"):
    print("get() says: no score")
if "Ana" in scores:
    print("in says: Ana has a score of", scores["Ana"])
Output
get() says: no score
in says: Ana has a score of 0

Questions people ask

What is the difference between dict.get() and dict[key]?

Both read a value. d[key] raises KeyError if the key is missing; d.get(key) returns None or your default.

Does get() add the key to the dictionary?

No. Use dict.setdefault() if you want a missing key added with a default value.

How do I get a value from a nested dictionary safely?

Chain get() calls with an empty dictionary as the default: data.get("user", {}).get("city").

Spotted a mistake on this page? Tell us