Start learning free

LESSON 129 OF 673 · DICTIONARIES

Deleting a Key in Python

Lesson

TL ; DR:

del removes a key and its value from a dictionary. The dictionary has one entry fewer.


toys = {"ball": 3, "doll": 2, "kite": 1}
del toys["kite"]

print(len(toys))   # 2
print(toys)        # {'ball': 3, 'doll': 2}


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Write del, then the dictionary with the key in square brackets. The key and its value go away together.

The length drops by 1. The key is gone, so "kite" in toys is now False.

Watch out: deleting a key that isn't there raises a KeyError. Check with in first when you aren't sure.

if "yoyo" in toys:
    del toys["yoyo"]

Setting a value to 0 doesn't delete its key. The entry stays and still counts in len.


Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print the length of animals again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check