🎓 A1Learner
🔍

Python Remove Dictionary Items

Removing a dictionary item takes a key and value pair out of a dictionary. Each removal tool fits a different job.

Remove with pop()

pop() removes the pair for a key. It returns the value that was removed.

stock = {"pens": 10, "books": 4}
sold = stock.pop("pens")
print(sold)
print(stock)

Remove the last pair

popitem() removes the last pair added. It returns that pair as a tuple.

stock = {"pens": 10, "books": 4}
pair = stock.popitem()
print(pair)
print(stock)

Remove with del

del removes the pair for a key. It returns nothing.

stock = {"pens": 10, "books": 4}
del stock["books"]
print(stock)

Remove everything

clear() empties the dictionary. The dictionary itself stays, with no pairs.

stock = {"pens": 10, "books": 4}
stock.clear()
print(stock)
print(len(stock))

Example

stock = {"apples": 3, "pears": 2}
print("Start:", stock)
while stock["apples"] > 0:
    stock["apples"] -= 1
    print("Sold an apple. Apples left:", stock["apples"])
empty = stock.pop("apples")
print("Empty shelf held:", empty)
print("Final:", stock)

Key points

  • Use pop() to remove a pair and get its value back
  • Use popitem() to remove the last pair added
  • Use del to remove a pair when you do not need its value
  • Use clear() to remove every pair at once
  • Use pop() when you know the key.

In this example, stock starts with three apples and two pears. The while loop runs while apples are left. Each round sells one apple and prints the new count. When the count reaches zero, the loop stops. Then pop() removes the empty apples pair and returns 0. Only the pears pair is left.

Note

popitem() removes the last added pair, not a pair you choose.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which code removes the pens pair and gives you its value?