Python 3 reference · Dictionary Methods
Python Dictionary get() Method
Return the value for a key, or a default (None unless given) if the key is missing, without raising KeyError.
Python 3 Since 3.0
Syntax
dict.get(key, default=None)
Parameters
| Parameter | Description |
|---|---|
key |
The key to look up. |
default optional |
Returned if the key is missing. Default: None |
Return value
The value or the default.
Examples
user = {"name": "Ada"}
print(user.get("name"), user.get("email"), user.get("email", "n/a"))
Output
Ada None n/a
counts = {}
for word in "a b a c a".split():
counts[word] = counts.get(word, 0) + 1
print(counts)
Output
{'a': 3, 'b': 1, 'c': 1}get() vs d[key]
d[key] raises KeyError when the key is missing; use it when the key must exist. d.get(key) returns
None (or your default), but can't tell a missing key from one whose value is None.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dict.setdefault()· Return the value for a key; if the key is missing, insert it with a default value first and return that.dict.pop()· Remove a key and return its value. Returns the default if given and the key is missing; otherwise raises KeyError.dict.items()· Return a live view of the dictionary's (key, value) pairs, used to loop over keys and values together.- Python Dictionaries · tutorial