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

ParameterDescription
key The key to look up.
default optional Returned if the key is missing. Default: None

Return value

The value or the default.

Examples

Safe lookupsTry it yourself
user = {"name": "Ada"}
print(user.get("name"), user.get("email"), user.get("email", "n/a"))

Output

Ada None n/a
Counting with get()Try it yourself
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

VersionChange
Python 3.0Added