Python Dictionary [] index operator

Using the index [] operator, the value in a dictionary can be retrieved or set. If the key doesn't exist, Python will throw a KeyError exception.

Syntax

Python
dictionary[key]

Parameters

ParameterDescription
key Required. The key of the item to return

Example

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

fish['guppy'] = 3
print(f'I now have {fish["guppy"]} guppies.')

try:
    numShark = fish['shark']
except Exception as e:
    print("I don't have any sharks.")

Output

I now have 3 guppies.
I don't have any sharks.