Removing an entry
Sometimes an entry has to go: a shop stops selling an item, or a player leaves the game. Write del, then the dictionary with the key in square brackets. The key and its value go away together, and the dictionary has one entry fewer.
animals = {"cat": 4, "dog": 2, "rabbit": 1}
del animals["rabbit"]
print(len(animals))
print(animals)
print("rabbit" in animals)
2
{'cat': 4, 'dog': 2}
False
Deleting a missing key
Deleting a key that isn't there raises a KeyError: del animals["hamster"] stops the program with KeyError: 'hamster'. When you aren't sure the key exists, check with in first:
if "hamster" in animals:
del animals["hamster"]
There is also a method, pop(key, default). It removes the key and returns its value, and with a default it doesn't fail on a missing key. animals.pop("hamster", None) returns None and changes nothing. Plain del is the clearest choice when you just want the entry gone and know it is there.
What stays
Only the deleted entry changes. The other entries keep their values, and they keep their order too: after the delete above, cat still comes before dog when the dictionary is printed or looped over.
Zero is not gone
Setting a value to 0 doesn't delete its key. The entry stays and still counts in len:
animals["dog"] = 0
print(len(animals))
print(animals)
2
{'cat': 4, 'dog': 0}
If "no dogs left" should mean the key is gone, you must delete it.
The lesson's task
A pet shop counts what it has for sale in animals: each key is a kind of animal and each value is how many the shop has. The starter code prints the length, then checks whether any rabbits are left.
The last rabbit just went home with a family. Between the first print and the check, delete the key "rabbit" with del, then print the length again. It is 3 before and 2 after. The check at the bottom now finds no "rabbit" key, so it takes the else branch.
animals = {"cat": 4, "dog": 2, "rabbit": 1}
print(len(animals))
del animals["rabbit"]
print(len(animals))
if "rabbit" in animals:
print("We still have rabbits")
else:
print("No rabbits left")
3
2
No rabbits left
Keeping the removed value, or emptying everything
When you still need the value of the entry you remove, use pop, which returns it. When you want to empty the whole dictionary, clear() removes every entry at once.
animals = {"cat": 4, "dog": 2, "rabbit": 1}
gone = animals.pop("rabbit")
print(gone, animals)
animals.clear()
print(animals, len(animals))
1 {'cat': 4, 'dog': 2}
{} 0
Both change the dictionary in place, like del. Unlike del, which is a statement, pop is a method call that gives back a result you can store.
Common mistakes
- Deleting in the wrong place. The delete must come after the first
printand before the second, so the two lengths differ. Put it before the first print and the output starts with2. - Using the value instead of the key.
del animals[1]looks for a key1, which isn't there, and raises aKeyError. A dictionary deletes by key. - Setting the count to 0.
animals["rabbit"] = 0keeps the key, so the length stays 3 and the check printsWe still have rabbits. - Deleting while looping over the same dictionary. A
forloop overanimalsthat deletes keys raisesRuntimeError: dictionary changed size during iteration. Loop over a copy of the keys instead,for k in list(animals):.
Key takeaways
del d[key]removes the key and its value, andlen(d)drops by 1.- A missing key raises a
KeyError; check withinor usepop(key, default). - A value of 0 is still an entry.
