Question
How can I delete an item from a dictionary in Python?
Also, if I do not want to modify the original dictionary, how can I create a new dictionary with one item removed?
This is about removing an entry from a Python dictionary, and also understanding how to produce a modified copy instead of changing the existing object in place.
Short Answer
By the end of this page, you will understand how to remove key-value pairs from a Python dictionary, when the original dictionary is changed, and how to create a new dictionary with a key omitted. You will also see common patterns, examples, and mistakes to avoid.
Concept
In Python, a dictionary stores data as key-value pairs. Removing an item means deleting one key and its associated value.
There are two main situations:
- Modify the existing dictionary
- Create a new dictionary without a specific key
This distinction matters because dictionaries are mutable, which means they can be changed after creation. If multiple parts of your program use the same dictionary, changing it in place may cause unexpected side effects.
Common ways to remove data include:
del d[key]— removes a key directlyd.pop(key)— removes a key and returns its value- dictionary comprehension — builds a new dictionary while excluding certain keys
Knowing when to mutate data and when to return a new copy is an important programming skill. In real programs, in-place updates are useful for performance and direct state changes, while creating a new dictionary is useful when you want safer, more predictable code.
Mental Model
Think of a dictionary like a labeled storage cabinet.
- Each key is a drawer label.
- Each value is what is stored inside that drawer.
Deleting an item means removing one labeled drawer from the cabinet.
There are two ways to do that:
- Change the cabinet you already have: remove the drawer from the original cabinet.
- Make a copy first: build a second cabinet that contains all the same drawers except one.
If other people are still using the original cabinet, making a new one avoids surprising them.
Syntax and Examples
Remove an item from the original dictionary
Use del when you want to delete a key from the existing dictionary.
data = {"name": "Ada", "age": 30, "city": "London"}
del data["age"]
print(data)
Output:
{'name': 'Ada', 'city': 'London'}
del changes the original dictionary.
Remove an item and get its value
Use pop() if you also want the removed value.
data = {"name": "Ada", "age": 30, "city": "London"}
removed_value = data.pop("age")
print(removed_value)
print(data)
Output:
{: , : }
Step by Step Execution
Consider this example:
original = {"a": 1, "b": 2, "c": 3}
new_dict = {k: v for k, v in original.items() if k != "b"}
Step by step:
-
originalis created with three key-value pairs:"a": 1"b": 2"c": 3
-
original.items()produces each key-value pair one at a time:("a", 1)("b", 2)("c", 3)
-
The comprehension checks each key using
if k != "b".- For
k = "a", the condition is true, so"a": 1is included.
- For
Real World Use Cases
Removing data from API responses
You may receive a dictionary from an API and want to remove sensitive fields before returning data to a client.
user = {"id": 1, "name": "Ada", "password": "secret"}
public_user = {k: v for k, v in user.items() if k != "password"}
Cleaning configuration data
You might delete temporary or deprecated configuration keys.
config = {"host": "localhost", "port": 8000, "debug": True}
del config["debug"]
Data transformation in scripts
When processing records, you may create modified copies instead of changing the original input.
record = {"name": "Ada", "score": 95, "internal_note": "reviewed"}
clean_record = {k: v for k, v in record.items() if k != "internal_note"}
Real Codebase Usage
In real projects, developers choose between mutation and copying based on intent.
Common patterns
1. Guarded removal
If a key might not exist, developers often avoid errors by checking first or using pop() with a default.
data = {"name": "Ada"}
data.pop("age", None)
2. Copy before modifying
This is common when functions should avoid side effects.
def without_password(user):
result = user.copy()
result.pop("password", None)
return result
3. Filtering fields for output
Dictionary comprehensions are common when building API responses or sanitized logs.
def public_fields(data):
hidden = {"password", "token"}
return {k: v for k, v in data.items() if k not in hidden}
Common Mistakes
1. Forgetting that del changes the original dictionary
data = {"x": 1, "y": 2}
alias = data
del data["x"]
print(alias)
Output:
{'y': 2}
alias points to the same dictionary, so it also reflects the change.
2. Using del on a missing key
data = {"x": 1}
del data["y"]
This raises a KeyError because "y" does not exist.
Safer version:
data.pop("y", None)
3. Thinking copy() makes a deep copy
Comparisons
| Approach | Changes original? | Returns removed value? | Raises error if key missing? | Best use |
|---|---|---|---|---|
del d[key] | Yes | No | Yes | Remove a known key directly |
d.pop(key) | Yes | Yes | Yes, unless default provided | Remove and use the value |
d.pop(key, default) | Yes | Yes | No | Safe removal when key may be missing |
d.copy() + del/pop | No |
Cheat Sheet
Quick reference
Delete from the original dictionary
del d[key]
- Removes
keyfromd - Raises
KeyErrorifkeydoes not exist
Remove and return the value
value = d.pop(key)
- Removes
key - Returns its value
- Raises
KeyErrorif missing
Safe removal if key might not exist
value = d.pop(key, None)
- Removes
keyif present - Returns
Noneif missing
Create a new dictionary without one key
new_d = {k: v for k, v in d.items() if k != key_to_remove}
FAQ
How do I delete a key from a dictionary in Python?
Use del d[key] if the key definitely exists, or d.pop(key, None) if it may be missing.
How do I remove a dictionary item without changing the original?
Create a new dictionary with a comprehension, or copy the dictionary first and remove the key from the copy.
What is the difference between del and pop() in Python?
del removes a key only. pop() removes the key and returns its value.
Does dict.copy() make a completely independent copy?
No. It creates a shallow copy. Nested dictionaries, lists, and other mutable values are still shared.
What happens if I delete a key that does not exist?
del d[key] raises KeyError. d.pop(key, None) avoids that error.
What is the best way to remove one key from a dictionary copy?
A clear pattern is:
new_d = d.copy()
new_d.pop("key", None)
Can I delete items from a dictionary while looping over it?
Mini Project
Description
Build a small Python utility that removes sensitive fields from a user record before printing or returning it. This demonstrates both in-place deletion and creating a safe cleaned copy without modifying the original data.
Goal
Create a function that returns a new dictionary with selected keys removed, while leaving the original dictionary unchanged.
Requirements
- Start with a dictionary representing a user record.
- Remove at least two sensitive keys such as
passwordandtoken. - Do not modify the original dictionary.
- Print both the original dictionary and the cleaned dictionary.
- Use a reusable function.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.