Python dictionary get() method
Look up a key, returning a default instead of an error when it is missing.
Syntax
dict.get(key, default=None)
The safe alternative to d[key], which raises KeyError for a missing key. The heart of the counting pattern counts[x] = counts.get(x, 0) + 1.
Parameters
| key | the key to look up |
| default | returned if the key is missing |
Return value
the value, or the default
Example
Code
stock = {"apples": 12, "pears": 0} print(stock.get("apples")) print(stock.get("kiwis")) print(stock.get("kiwis", 0)) counts = {} for w in "a b a c a".split(): counts[w] = counts.get(w, 0) + 1 print(counts)
Output
12
None
0
{'a': 3, 'b': 1, 'c': 1}
Good to know.
stock.get("pears") or 5 gives 5 even though pears is 0, because 0 is falsy. Use the default argument instead.Related
Learn it step by step in the free lesson Dictionaries & Sets, with exercises that check your answers.