Python Dictionary get() Method

Short answer
dict.get(key, default=None) returns the value for key if it exists, otherwise default (which is None unless you pass something else). It never raises a KeyError and never changes the dictionary.

Reading prices["kiwi"] crashes with a KeyError when the key is missing. get() is the safe alternative: you say what to use when the key is absent and the program carries on. It is one of the most used dictionary methods, especially for optional settings, user input and data loaded from files.

Because get() only reads, it is also the right tool when you must not add keys by accident. If you want to read and create the entry in one step, use dict.setdefault() instead.

Quick facts
Syntaxmy_dict.get(key) or my_dict.get(key, default)
Parameterskey: the key to look up; default: value returned when the key is missing (optional, defaults to None)
ReturnsThe stored value, or default if the key is not in the dictionary
Changes the dictionary?No
Time complexityO(1) on average

How dict.get() works with and without a default

get() looks the key up exactly like square brackets do, using the key's hash. The only difference is what happens on a miss. With d[key] Python raises KeyError; with d.get(key) it returns None; with d.get(key, fallback) it returns fallback.

Python
stock = {"apples": 12, "pears": 0}
print(stock.get("apples"))
print(stock.get("kiwis"))
print(stock.get("kiwis", 5))
print(stock)

Notice that the last line shows the dictionary unchanged: the missing key "kiwis" was not added.

get() versus square brackets and the in operator

Pick the tool by what a missing key means in your program. If a missing key is a bug, you want the loud KeyError, so use d[key]. If a missing key is normal (an optional setting, a word you have not counted yet), use get(). If you only need to know whether a key exists, use key in d, which checks the keys and ignores values.

Five ways to look at one key.
ToolKey presentKey missingAdds the key?
d[key]The valueRaises KeyErrorNo
d.get(key)The valueNoneNo
d.get(key, x)The valuexNo
d.setdefault(key, x)The valuex (and stores it)Yes, when missing
key in dTrueFalseNo

The default is only used when the key is absent

A very common surprise: get() returns the stored value even when it is falsy. If the key "pears" holds 0 or None, that is what you get back, not the default. The default only replaces a missing key.

If you also want to treat a stored None as "no value", add an or or an explicit check, for example d.get("pears") or 5. Be careful, though: or also replaces 0 and empty strings, so use it only when those mean "unset" for you.

The default expression is evaluated every time, even when the key exists. Passing something expensive such as d.get(k, load_from_disk()) calls load_from_disk() on every lookup. For costly fallbacks, check with in first. To count things, combine get() with + 1, as in the second example, or see looping through a dictionary for more patterns.

Examples you can run

Press Run, then edit the code and run it again.

Read an optional setting with a default

get() keeps the program running when a setting was not provided.

Read an optional setting with a default
settings = {"theme": "dark", "font_size": 14}
print(settings.get("theme", "light"))
print(settings.get("language", "en"))
print(settings.get("autosave"))
Expected outputdark
en
None

Count words with get()

counts.get(word, 0) + 1 starts a missing word at zero, then adds one. No KeyError, no if needed.

Count words with get()
words = ["red", "blue", "red", "green", "red", "blue"]
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
Expected output{'red': 3, 'blue': 2, 'green': 1}

A stored falsy value is not replaced

The key exists, so its value 0 wins over the default.

A stored falsy value is not replaced
scores = {"asha": 0}
print(scores.get("asha", 100))
print(scores.get("ravi", 100))
Expected output0
100

Common mistakes

Calling get() with square brackets

✗ Wrong

prices = {"pen": 3}
print(prices.get["pen"])
TypeError: 'builtin_function_or_method' object is not subscriptable

✓ Right

prices = {"pen": 3}
print(prices.get("pen"))

get is a method, so call it with parentheses: prices.get("pen").

Doing math on the None result

✗ Wrong

cart = {"pen": 2}
total = cart.get("book") + 1
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

✓ Right

cart = {"pen": 2}
total = cart.get("book", 0) + 1
print(total)

Without a default, a missing key gives None. Pass a numeric default such as 0 when you plan to calculate with the result.

Expecting get() to add the key

✗ Wrong

stock = {}
stock.get("apples", 10)
print(stock)
{} (the dictionary is still empty)

✓ Right

stock = {}
stock.setdefault("apples", 10)
print(stock)

get() never stores anything. Use setdefault() or assign with stock["apples"] = 10 if you want the key created.

Python Dictionary get() Method: questions people ask

What does dict.get() return if the key is not found?

It returns None, or the default value you passed as the second argument. It does not raise a KeyError.

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

dict[key] raises a KeyError for a missing key, while dict.get(key) returns None or your default. Use brackets when a missing key is a bug and get() when it is expected.

Does dict.get() add the key to the dictionary?

No. get() only reads. To read and create the key in one call, use setdefault().

Keep learning

Step-by-step lessons:
Python DictionariesPython Dictionary MethodsPython KeyError: What It Means and How to Fix It

Related:
Python Dictionary setdefault() MethodPython Dictionary pop() MethodPython Dictionary items() MethodHow to Loop Through a Dictionary in Python

More in dictionary methods:
Python Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodPython Dictionary update() MethodPython Dictionary pop() MethodPython Dictionary popitem() MethodPython Dictionary setdefault() MethodPython Dictionary clear() Method See all →