Question

Delete an Element from a Dictionary in Python

pythondictionarydel

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 directly
  • d.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.

Take Quiz

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:

30
{'name': 'Ada', 'city': 'London'}

Create a new dictionary without changing the original

Use a dictionary comprehension to exclude one key.

original = {"name": "Ada", "age": 30, "city": "London"}
new_dict = {key: value for key, value in original.items() if key != "age"}

print(original)
print(new_dict)

Output:

{'name': 'Ada', 'age': 30, 'city': 'London'}
{'name': 'Ada', 'city': 'London'}

The original dictionary stays unchanged.

Make a copy, then delete from the copy

Another simple option is to copy first.

original = {"name": "Ada", "age": 30, "city": "London"}
new_dict = original.copy()
del new_dict["age"]

print(original)
print(new_dict)

This is often easier to read when removing only one key.

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:

  1. original is created with three key-value pairs:

    • "a": 1
    • "b": 2
    • "c": 3
  2. original.items() produces each key-value pair one at a time:

    • ("a", 1)
    • ("b", 2)
    • ("c", 3)
  3. The comprehension checks each key using if k != "b".

    • For k = "a", the condition is true, so "a": 1 is included.
    • For k = "b", the condition is false, so "b": 2 is skipped.
    • For k = "c", the condition is true, so "c": 3 is included.
  4. A new dictionary is built from the included pairs:

{"a": 1, "c": 3}
  1. original is unchanged because the comprehension creates a separate dictionary object.

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"}

State updates in applications

Some codebases prefer returning new objects rather than mutating existing ones, especially in predictable state management patterns.

Take Quiz

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}

4. Validation and cleanup

Before saving or serializing data, code may remove empty or forbidden keys.

def remove_none_values(data):
    return {k: v for k, v in data.items() if v is not None}

These patterns make code safer, easier to test, and easier to reason about.

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

data = {"user": {"name": "Ada"}}
copy_data = data.copy()
copy_data["user"]["name"] = "Grace"

print(data)

Output:

{'user': {'name': 'Grace'}}

copy() makes a shallow copy. Nested objects are still shared.

4. Modifying a dictionary while iterating over it

Broken example:

data = {"a": 1, "b": 2, "c": 3}
for key in data:
    if key == "b":
        del data[key]

This can raise an error because the dictionary size changes during iteration.

Safer approach:

data = {"a": 1, "b": 2, "c": 3}
new_data = {k: v for k, v in data.items() if k != "b"}

5. Using remove() on a dictionary

remove() is a list method, not a dictionary method.

Incorrect:

data = {"a": 1}
# data.remove("a")

Use del or pop() instead.

Comparisons

ApproachChanges original?Returns removed value?Raises error if key missing?Best use
del d[key]YesNoYesRemove a known key directly
d.pop(key)YesYesYes, unless default providedRemove and use the value
d.pop(key, default)YesYesNoSafe removal when key may be missing
d.copy() + del/popNoOptionalDepends on method usedKeep original unchanged
Dictionary comprehensionNoNoNoBuild a filtered new dictionary

copy() plus delete vs dictionary comprehension

MethodGood whenExample
copy() + deleteRemoving one or a few specific keysnew = d.copy(); new.pop("x", None)
Dictionary comprehensionFiltering based on rules or many keys{k: v for k, v in d.items() if k != "x"}

In practice:

  • Use del for direct in-place deletion.
  • Use pop() when you want the removed value or safer handling.
  • Use comprehension when you want a clean new dictionary.
Take Quiz

Cheat Sheet

Quick reference

Delete from the original dictionary

del d[key]
  • Removes key from d
  • Raises KeyError if key does not exist

Remove and return the value

value = d.pop(key)
  • Removes key
  • Returns its value
  • Raises KeyError if missing

Safe removal if key might not exist

value = d.pop(key, None)
  • Removes key if present
  • Returns None if missing

Create a new dictionary without one key

new_d = {k: v for k, v in d.items() if k != key_to_remove}
  • Original dictionary is unchanged

Copy first, then remove

new_d = d.copy()
new_d.pop(key_to_remove, None)
  • Useful when removing only a small number of keys

Important rule

dict.copy() is a shallow copy, not a deep copy.

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?

Not safely in most cases. It is better to build a new dictionary or iterate over a separate list of keys.

Take Quiz

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

  1. Start with a dictionary representing a user record.
  2. Remove at least two sensitive keys such as password and token.
  3. Do not modify the original dictionary.
  4. Print both the original dictionary and the cleaned dictionary.
  5. Use a reusable function.
Take Quiz

Keep learning

Related questions

View more