get() - Returns the value of the specified key

Returns the value of the specified 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'