Start learning free

LESSON 129 OF 673 · DICTIONARIES

Deleting a Key from a Python Dictionary with del

Lesson Read the full explanation

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

    PYTHON · DICTIONARIES

    Deleting Dictionary Keys in Python, explained

    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 print and before the second, so the two lengths differ. Put it before the first print and the output starts with 2.
    • Using the value instead of the key. del animals[1] looks for a key 1, which isn't there, and raises a KeyError. A dictionary deletes by key.
    • Setting the count to 0. animals["rabbit"] = 0 keeps the key, so the length stays 3 and the check prints We still have rabbits.
    • Deleting while looping over the same dictionary. A for loop over animals that deletes keys raises RuntimeError: 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, and len(d) drops by 1.
    • A missing key raises a KeyError; check with in or use pop(key, default).
    • A value of 0 is still an entry.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free