Python Dictionary get() Method

Returns the value of the specified key.

Syntax

Python
dictionary.get(key)
dictionary.get(key, default)

Parameters

ParameterDescription
key Required. The key of the value to return
default Optional. The value to be returned if the dictionary has no item keyed by key.

Example

Python
fish = {
    'guppy': 2,
    'zebra' : 5,
    'betta': 10
}

print(f'I have {fish.get("guppy")} guppy fish.')

Output

I have 2 guppy fish.

Notes

The reason to use get() instead of a dictionary index [] is that you can provide a default value for when the key is missing in the dictionary.

Example

Python
fish = {
'guppy': 2,
'zebra' : 5,
'betta': 10
}

print(f'I have {fish.get("shark", 0)} shark.')

# This throws an exception:
print(f'I have {fish["shark"]} shark.')

Output

I have 0 shark.
Traceback (most recent call last):
  File "Dictionaries.py", line 73, in <module>
    print(f'I have {fish["shark"]} shark.')
KeyError: 'shark'