Removing Items
Concepts covered: Dict Methods
Most dictionaries also lose pairs, the way a cart empties or a session ends. Python gives 3 ways to take pairs out, and they differ in what they hand back and in what they do when the key is already gone.
del removes a pair
user = {"name": "Alice", "age": 28, "city": "Seattle"}
print("Before:", user)
del user["city"]
print("After del:", user)Before: {'name': 'Alice', 'age': 28, 'city': 'Seattle'}
After del: {'name': 'Alice', 'age': 28}
del user["city"] removes both the key and its value; the dictionary shrinks from 3 pairs to 2 and "city" is gone as if it had never been written. del is a statement rather than a function, so it hands nothing back: there is no way to write x = del user["city"].
user = {"name": "Alice", "age": 28}
del user["age"]
print(user)
del user["age"]Deleting a key that is absent raises the same KeyError as reading one. The first del succeeds, the print shows the 1 remaining pair, and the second del stops the program. When a program might delete the same key twice, del on its own is unsafe.
pop removes and returns
user = {"name": "Alice", "age": 28, "city": "Seattle"}
# Remove and get the value
city = user.pop("city")
print("Removed city:", city)
print("Remaining:", user)
# Safe pop with default (key doesn't exist)
country = user.pop("country", "Unknown")
print("Country:", country)Removed city: Seattle
Remaining: {'name': 'Alice', 'age': 28}
Country: Unknown
user.pop("city") does 2 things: it removes the pair and it returns the value, so city holds "Seattle" after the call. That makes pop the tool when you still need the value, such as moving an item from a cart to an order. The second call shows the safe form: user.pop("country", "Unknown") finds no "country" key, leaves the dictionary alone, and returns the default.
scores = {"ana": 91, "ben": 78}
removed = scores.pop("ben")
print(removed)
print(scores)
print(scores.pop("cara", 0))
print(scores.pop("cara"))pop with 1 argument behaves like del: a missing key is a KeyError. pop with 2 arguments never raises for a missing key, because the second argument is what to return when there's nothing to remove. The traceback here comes from the final line only; the 3 prints before it all ran and their output stays on screen.
clear empties everything
cart = {"apple": 3, "pear": 1}
cart.clear()
print(cart)
print(len(cart))Output:
{}
0cart.clear() removes every pair at once, leaving the dictionary with 0 pairs. The name cart still refers to it, and new pairs can be added afterwards with bracket assignment. Calling clear() on an already empty dictionary does nothing and raises nothing.
| Operation | Hands back | Key missing |
|---|---|---|
| del d[key] | Nothing | KeyError |
| d.pop(key) | The removed value | KeyError |
| d.pop(key, default) | The removed value, or the default | Returns the default, no error |
| d.clear() | Nothing | No key involved, never errors |
- Do
- Use pop with a default when a key may already be gone
- Use pop when you need the value you are removing
- Use del when the key must exist and a crash should flag the bug
- Avoid
- Don't call del twice on the same key without a check between
- Do not use pop(key) without a default for optional keys
- Do not remove pairs one at a time to empty a dictionary; use clear
Practice
Real programs mix the removal tools, and the order of the calls decides what each one finds. Trace this session cleanup line by line before you run it:
session = {"user": "ana", "token": "x91", "cart": 2}
token = session.pop("token")
del session["cart"]
print(token)
print(session.pop("cart", "already gone"))
print(session)Output:
x91
already gone
{'user': 'ana'}Line 2 takes "token" out and keeps its value in token. Line 3 removes "cart", so by line 5 the key is absent and pop hands back its default instead of a count. Change line 5 to session.pop("cart") and the program would print x91, then stop with KeyError: 'cart'. Only "user" is left at the end.
What does the print statement show?
cart = {"apple": 2, "pear": 1, "plum": 4}
taken = cart.pop("pear")
del cart["plum"]
print(taken, cart.pop("plum", "gone"), cart)- 1 gone {'apple': 2}
- 1 4 {'apple': 2}
- A traceback, because "plum" was already removed
- 1 gone {'apple': 2, 'pear': 1}
About this lesson
This section is part of the Dictionaries: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.