Remove Key from Dictionary in Python

Learn how to remove a key from a Python dictionary using pop(), del, dictionary comprehension, and safe methods to avoid KeyError when the key may not exist.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Remove Key from Dictionary in Python

Python dictionaries are mutable: you can delete key-value pairs in place. The two methods you will see most often are pop() and del. Which one to use depends on whether the key always exists, whether you need the removed value, and whether a missing key should raise an error or be ignored safely.

This page shows how to remove one key, several keys, keys by condition, and keys with empty or None values—plus popitem() and clear() when those fit. For dict basics, see Python dictionary. When keys live inside nested mappings, see nested dictionary in Python; to merge remaining keys from another dict, see merge two dictionaries.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Remove key from dictionary: quick reference

Task Best method
Remove a key and get its value pop()
Remove a key only if it exists pop(key, default)
Remove a key when you are sure it exists del dict[key]
Remove multiple known keys Loop over keys with pop()
Remove keys by condition Dictionary comprehension
Remove the last inserted item popitem()
Remove all keys clear()

Use pop() when you want safer removal or need the deleted value. Use del when the key must exist. Use dictionary comprehension when you want a new filtered dictionary.


Method 1: Remove a key using pop()

dict.pop(key) removes the key and returns its value. This is usually the best starting point for beginners and when you need the deleted value after removal.

python
student = {
    "sid": 22146,
    "name": "Jim",
    "rank": 15874,
    "projects": 2,
}

removed = student.pop("projects")
print(removed)
print(student)
Output

You should see 2, then a dict without "projects".

If the key does not exist and you omit a default, Python raises KeyError.


Method 2: Remove a key safely without KeyError

Use pop(key, default) when the key may or may not exist. If the key is present, it is removed and its value is returned. If not, Python returns default and leaves the dict unchanged.

python
student = {"name": "Jim", "rank": 15874}

print(student.pop("rank", None))
print(student)

print(student.pop("rank", None))
print(student)
Output

You should see 15874 and a dict without "rank", then None twice—the second pop("rank", None) does not error.

This pattern is the usual answer when search intent is “remove key if exists” without crashing.


Method 3: Delete a dictionary key using del

del dict[key] removes the pair in place and does not return the value. It raises KeyError if the key is missing.

python
student = {"name": "Jim", "rank": 15874, "projects": 2}

del student["rank"]
print(student)
Output

You should see a dict without "rank".

Use del when you are sure the key exists and you do not need the old value. Prefer del student["rank"] over del(student['rank'])del is a statement, not a function.

Comparison: pop() returns the removed value; del only deletes.


pop() vs del: which one should you use?

Situation Use
Need the removed value pop()
Key may be missing pop(key, default)
Key must exist del
Want shorter direct deletion del
Want safer code pop(key, default)

Remove multiple keys from a dictionary

Loop over a list or tuple of keys and call pop(key, None) so missing names do not raise:

python
student = {
    "name": "Jim",
    "rank": 15874,
    "projects": 2,
    "publications": 5,
}

for key in ("rank", "projects", "publications", "missing"):
    student.pop(key, None)

print(student)
Output

You should see {'name': 'Jim'}. Adjust the tuple to the keys you need to drop.


Remove keys from dictionary by condition

A dictionary comprehension builds a new dict that omits keys matching a rule. The original dict stays unchanged unless you reassign:

python
student = {
    "sid": "",
    "name": "Jim",
    "note": None,
    "rank": 15874,
    "temp_flag": True,
}

filtered = {
    k: v
    for k, v in student.items()
    if not k.startswith("temp_")
}

print(filtered)
print(student)
Output

You should see a filtered dict without temp_flag, while student still has all original keys.

Common patterns:

  • Drop keys with empty strings: if v != ""
  • Drop keys where value is None: if v is not None
  • Drop keys by prefix: if not k.startswith("meta_")
  • Drop keys failing a test: if v > 0, if isinstance(v, str), etc.

Remove keys with empty or None values

Empty string and None are not the same. Pick the rule that matches your data:

python
record = {"sid": "", "name": "Jim", "note": None, "score": 0}

without_empty = {k: v for k, v in record.items() if v != ""}
without_none = {k: v for k, v in record.items() if v is not None}
without_falsy = {k: v for k, v in record.items() if v}

print(without_empty)
print(without_none)
print(without_falsy)
Output

without_empty keeps note, score, and name. without_none keeps sid (empty string) and others. without_falsy also removes 0 and "" because they are falsy.

Compare values with !=, not is not, for strings and most objects. is not checks identity, not equality—value is not "" is the wrong tool for “not an empty string.”


Remove the last inserted item using popitem()

popitem() does not remove a named key. It removes and returns the last inserted pair (LIFO since Python 3.7). On an empty dict it raises KeyError.

python
student = {"name": "Jim", "rank": 15874}
student["projects"] = 2

print(student.popitem())
print(student)
Output

You should see ('projects', 2) removed last, then the remaining dict.

Use this for stack-like dict behavior—not when you need to delete a specific key.


Remove all keys using clear()

clear() removes every key-value pair from the same dict object:

python
student = {"name": "Jim", "rank": 15874}
student.clear()
print(student)
Output

You should see {}. Use clear() only when you want an empty dictionary, not to drop a single key.


Remove a key without changing the original dictionary

Dictionaries are mutable and passed by reference. To keep the original while producing a version without one key, use comprehension or copy():

python
student = {"name": "Jim", "rank": 15874, "projects": 2}

trimmed = {k: v for k, v in student.items() if k != "rank"}
print(student)
print(trimmed)
Output

Both dicts print—student still has "rank". Alternatively:

python
copy = student.copy()
copy.pop("rank", None)
Output

Other code holding student still sees the full dict; only copy is modified.


Mistakes to avoid when removing dictionary keys

  • Using del dict[key] when the key might be missing—use pop(key, default) instead.
  • Using popitem() to remove a specific key—it only removes the last inserted pair.
  • Using clear() when you only need to drop one or a few keys.
  • Modifying a dict while iterating over its live view (for k in d: then del d[k])—collect keys to delete first, or iterate over list(d).
  • Using is / is not instead of == / != when comparing string or numeric values.
  • Saying “duplicate keys” when the problem is duplicate values—dict keys are already unique; deduping values is a different task.

Summary

Use pop(key) to remove a key and get its value. Use pop(key, default) to avoid KeyError when the key may be absent. Use del dict[key] when the key definitely exists and you do not need the value. Use dictionary comprehension (or copy() + pop) to filter keys or keep the original dict unchanged. Use popitem() for the last inserted pair, and clear() only to empty the entire dictionary.

See the official dict documentation for pop, popitem, and clear.


Frequently Asked Questions

1. What is the best way to remove a key from a Python dictionary?

Use pop(key) when you want the removed value; use pop(key, default) when the key might be missing; use del dict[key] when the key must exist and you do not need the value.

2. What is the difference between pop() and del for dictionary keys?

pop() removes the key and returns its value (optional default avoids KeyError); del removes the key and returns nothing, raising KeyError if the key is absent.

3. How do I remove a key without KeyError?

Call pop(key, None) or pop(key, default) so Python returns the default instead of raising when the key is missing.

4. Does dictionary comprehension modify the original dictionary?

No—it builds a new dict. Assign back to the same variable or use copy() first if you need to keep the original unchanged elsewhere.

5. What does popitem() do?

It removes and returns the last inserted key-value pair (LIFO since Python 3.7); it does not remove a specific key by name.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …