setdefault() - Returns the value of the specified key. If the key does not exist: insert

Returns the value of the item with the specified key.  If the key doesn't exist, the key-value pair is inserted with the specified value and the specified value is returned.


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

# The 'guppy' key exists, so the dictionary in unchanged.
numGuppies = fish.setdefault('guppy', 10)
print(f'I still have {numGuppies} guppies: {fish}')

# But we didn't have any shark!
numShark = fish.setdefault('shark', 1)
print(f'I have {numShark} shark!')


I still have 2 guppies: {'guppy': 2, 'zebra': 5, 'betta': 10}
I have 1 shark!